>>> s ="We all love Python">>> s.split()#基于空格分隔['We','all','love','Python']>>> x ="shiyanlou:is:waiting">>> x.split(':')#基于冒号分隔['shiyanlou','is','waiting']>>>"-".join("GNU/Linux is great".split())#基于空格分隔,用-连接'GNU/Linux-is-great'>>> s ="shi yan lou">>> s.title()#输出标题样式'Shi Yan Lou'>>> z = s.upper()#大写>>> z
'SHI YAN LOU'>>> z.lower()#小写'shi yan lou'>>> s ="I am A pRoGraMMer">> s.swapcase()#大小写反写'i AM a PrOgRAmmER'>>> s ="jdwb 2323bjb">>> s.isalnum()False>>> s ="jdwb2323bjb">>> s.isalnum()True>>> s ="SankarshanSir">>> s.isalpha()True>>> s ="Sankarshan Sir">>> s.isalpha()False>>> s ="1234">>> s.isdigit()# 检查字符串是否所有字符为数字True>>> s ="ShiYanLou is coming">>> s.islower()# 检查字符串是否所有字符为小写False>>> s ="CHINA">>> s.isupper()# 检查字符串是否所有字符为大写True>>> s ="Shiyanlou Is Coming">>> s.istitle()# To 检查字符串是否为标题样式True>>> s =" a bc\n ">>> s.strip()'a bc'>>> s ="www.foss.in">>> s.lstrip("cwsd.")#删除在字符串左边出现的'c','w','s','d','.'字符'foss.in'>>> s.rstrip("cnwdi.")#删除在字符串右边出现的'c','n','w','d','i','.'字符'www.foss'>>> s ="faulty for a reason">>> s.find("for")7>>> s.find("fora")-1>>> s.startswith("fa")# 检查字符串是否以 fa 开头True>>> s.endswith("reason")# 检查字符串是否以 reason 结尾True
判断字符串是否是回文
#!/usr/bin/env python3
s =input("Please enter a string: ")
z = s[::-1]#把输入的字符串s 进行倒序处理形成新的字符串zif s == z:print("The string is a palindrome")else:print("The string is not a palindrome")
单词计数
%s 字符串(用 str() 函数进行字符串转换)
%r 字符串(用 repr() 函数进行字符串转换)
%d 十进制整数
%f 浮点数
%% 字符“%”
#!/usr/bin/env python3
s =input("Enter a line: ")#将输入的字符串按空格分隔,计数,填入%d的位置print("The number of words in the line are %d"%(len(s.split(" "))))