1 strip()方法
去除字符串中指定的字符
s = "123abc "
s.strip(" ") # 去除空格
s = "123abc"
2 replace()方法
替换指定字符为其他字符
s = "123abc "
s.replace(" ","1") # 将空格替换为1
s = "123abc111"
去除 回车\r 和 换行符\n
s.replace('\n', '').replace('\r', '')
3 大小写转换
str = "www.runoob.com"
print(str.upper()) # 把所有字符中的小写字母转换成大写字母
print(str.lower()) # 把所有字符中的大写字母转换成小写字母
print(str.capitalize()) # 把第一个字母转化为大写字母,其余小写
print(str.title()) # 把每个单词的第一个字母转化为大写,其余小写
WWW.RUNOOB.COM
www.runoob.com
Www.runoob.com
Www.Runoob.Com
4 isalnum()方法
检测字符串是否由 字母 和 数字 组成
str = "this2009"; # 字符中没有空格
print(str.isalnum());
str = "this is string example....wow!!!"; # 字符中有空格
print(str.isalnum());
True
False
5 find()方法
从下标0开始,查找在字符串里第一个出现的子串的位置(索引号)
info = 'abca'
print(info.find('a')) # 返回结果:0
>> 0
6 字符串去重
使用 set() 方法
s = "123ab11111"
b = set(s)
>> {'a', 'b', '2', '3', '1'}
a = "".join(list(b))
>> 'ab231'
7 拼接与拆分
拼接 join() 方法
拆分 split() 方法
str = "this is string example....wow!!!"
print (str.split( )) # 以空格为分隔符
print (str.split('i',1)) # 以 i 为分隔符
print (str.split('w')) # 以 w 为分隔符
['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']