判断是否全是字母
"python".isalpha() # 返回True
"2python".isalpha() # 返回False
根据分隔符分割字符串
a = "I,LOVE,PYTHON"
a.split(",")
# 结果:['I','LOVE','PYTHON']
去掉字符串两头的空格及回车符
str.strip() # 去掉字符串两边的空格及回车符
str.lstrip() # 去掉字符串左边的空格及回车符
str.rstrip() # 去掉字符串右边的空格及回车符
字符大小写的转换
str.upper() # 字母转化为大写
str.lower() # 字母转化为小写
str.capitalize() # 将首字母转化为大写
str.isupper() # 判断字母是否全是大写
str.islower() # 判断字母是否全是小写
str.istitle() # 判断字符串中是否所有单词的首字母为大写,且其他字母为小写
用join()拼接字符串
s_list = ['www','baidu','com']
"*".join(s_list)
# 返回结果:'www*baidu*com'
用center()方法填充字符串
str = 'runoob'
str.center(20, '*') # str.center(width[, fillchar])
# 返回结果:'*******runoob*******'
统计字符串里某个字符出现的次数
# 语法:str.count(sub, start= 0,end=len(string))
str = "this is string example....wow!!!";
sub = "wow";
print str.count(sub)
# 返回结果:1
用于判断字符串是否以指定后缀结尾
"""
语法:str.endswith(suffix[, start[, end]])
参数
suffix -- 该参数可以是一个字符串或者是一个元素。
start -- 字符串中的开始位置。
end -- 字符中结束位置。
"""
str = "this is string example....wow!!!";
suffix = "wow!!!";
print str.endswith(suffix);
# 返回结果:True
find()方法检测字符串中是否包含子字符串
如果包含子字符串返回开始的索引值,否则返回-1
"""
语法:
str.find(str, beg=0, end=len(string))
参数
str -- 指定检索的字符串
beg -- 开始索引,默认为0。
end -- 结束索引,默认为字符串的长度。
"""
str1 = "this is string example....wow!!!";
str2 = "exam";
print str1.find(str2);
# 结果:15,查不到返回-1
index()方法方法检测字符串中是否包含子字符串
用法与 find() 方法一样,如果包含子字符串返回开始的索引值,不同的是找不到子字符串会抛出异常。
把字符串中的 old(旧字符串) 替换成 new(新字符串)
"""
语法:
str.replace(old, new[, max])
参数
old -- 将被替换的子字符串。
new -- 新字符串,用于替换old子字符串。
max -- 可选字符串, 替换不超过 max 次
"""
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was"); # 结果:thwas was string example....wow!!! thwas was really string
print str.replace("is", "was", 3); # 结果:thwas was string example....wow!!! thwas is really string