大小写变换
str = 'i\'am string'
print str.lower() #小写 i'am string
print str.upper() #大写 I'AM STRING
print str.swapcase() #大小写互换 I'AM STRING
print str.capitalize() #首字母大写 I'am string
print str.title() #每个单词的首字母大写 I'Am String
字符串输出时的格式
#输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格
print str.ljust(20, '#') #左对齐 i'am string#########
print str.rjust(20, '#') #右对齐 #########i'am string
print str.center(20, '#') #居中 ####i'am string#####
print str.zfill(20) #把S变成width长,并在右对齐,不足部分用0补足000000000i'am string
字符串查找
#S.find(substr, [start, [end]])
#返回S中出现substr的第一个字母的标号,如果S中没有substr则返回-1。start和end作用就相当于在S[start:end]中搜索
print str.find('str', 0, 7)
print str.index('str', 0) #与find()相同,只是在S中没有substr时,会返回一个运行时错误
#返回S中最后出现的substr的第一个字母的标号,如果S中没有substr则返回-1,也就是说从右边算起的第一次出现的substr的首字母标号
print str.rfind('str', 0, 7)
print str.rindex('str', 0)
print str.count('str', 0, 7) #统计substr出现的次数
字符串替换
#S.replace(oldstr, newstr, [count])
print str.replace('str', 'newStr', 2)
str1 = "aaPythonaa"
print str1.strip('a') #把S中前后chars中有的字符全部去掉 Python
print str1.lstrip('a') #Pythonaa
print str1.rstrip('a') #aaPython
str2 = "asas\tasas\tYYYY"
print str2.expandtabs(3) #把S中的tab字符替换成空格,默认是每个tab替换为8个空格 asas asas YYYY
字符串分割及组合
str3 = ",a,a,a,a,a,ab,"
#以sep为分隔符,把S分成一个list。maxsplit表示分割的次数。默认的分割符为空白字符
print str3.split(',', 3) #['', 'a', 'a', 'a,a,a,ab,']
print str3.rsplit(',', 3) #[',a,a,a,a', 'a', 'ab', '']
str4 = '''string
python
hello
world'''
print str4.splitlines(False) #['string', 'python', 'hello', 'world']
str5 = ['java','c','perl','python']
print " and ".join(str5) #java and c and perl and python