字符串类型转换
int()
将符合整数格式的字符串转换为整数。
int("589") == 589
int(4.56) == 4
float()
将符合浮点数格式的字符串转换为浮点数。
float("45.6") == 45.6
float(5) == 5.0
str()
将整数和浮点数转换为字符串。
str(567) == '567'
str(45.6) == '45.6'
str(0xcc) == '204'
字符串大小写转换
lower()
大写全转换小写
>>> 'ABC,ABC,ABC,ABC,ABC,ABC,ABC'.lower()
abc,abc,abc,abc,abc,abc,abc
upper()
小写全转换大写
>>> 'abc,abc,abc,abc,abc,abc,abc'.upper()
ABC,ABC,ABC,ABC,ABC,ABC,ABC
title()
单词首字母转换为大写
>>> 'abc,abc,abc,abc,abc,abc,abc'.title()
Abc,Abc,Abc,Abc,Abc,Abc,Abc
capitalize()
语句首字母转换为大写
>>> 'abc,abc,abc,abc,abc,abc,abc'.capitalize()
Abc,abc,abc,abc,abc,abc,abc
swapcase()
大小写互换
>>> 'Abc,Abc,Abc,Abc,Abc,Abc,Abc'.swapcase()
aBC,aBC,aBC,aBC,aBC,aBC,aBC
查找统计
find()
显示特定字符串的位置序列号,无查找到返回值【-1】
>>> '1,2,3,4,5,6,7,8,9,10'.find('4')
6
>>> 'this is string '. find('is')
8
index()
索引,字符串位置并输出序列号,无索引到会报错
>>> '1,2,3,4,5,6,7,8,9,10'.index('4')
6
count()
统计字符串出现次数
>>> 'abc,abc,abc,abc,abc,abc,abc'.count('a')
7
len()
统计字符串长度
>>> print(len('abc,abc,abc,abc,abc,abc,abc'))
27
匹配判断
in()
判断字符串包含关系
>>> a = "123456789"
>>> b = "2" in a
>>> print(b)
True
startswith()
匹配开始字符串是否一致
>>> 'This is test'.startswith('This')
True
endswith()
匹配结束字符串是否一致
>>> 'This is test'.endswith('test')
True
isalnum()
判断字符串是否只包含数字和字母
>>> '123@test.com'.isalnum()
False
isalpha()
判断字符串是否只包含字母
>>> 'This is test'.isalpha()
False
>>> 'Thisistest'.isalpha()
True
isdecimal()
判断字符串是否只包含数字
>>> '123456789'.isdecimal()
True
匹配替换
切片取字符串范围
取字符串前四位
a = "123456789"
print(a[0:4])
去除字符串后四位
a = "123456789"
print(a[:-4])
replace()
匹配项替换
>>> '1,2,3,4,5,6,7,8,8,10'.replace('6','A')
'1,2,3,4,5,A,7,8,8,10'
translate()
匹配项多项替换
>>> from string import maketrans
>>> intab = "acg"
>>> outtab = "123"
>>> trantab = maketrans(intab, outtab)
>>> str = "a,b,c,d,e,f,g";
>>> print str.translate(trantab);
1,b,2,d,e,f,3
字符串规整
join()
添加连接符
>>> a = ['1','2','3','4','5','6','7','8','9','10']
>>> b = '+'
>>> b.join(a)
'1+2+3+4+5+6+7+8+9+10'
或
>>> ('+').join(['1','2','3','4','5','6','7','8','9','10'])
'1+2+3+4+5+6+7+8+9+10'
split()
去除连接符
>>> '1+2+3+4+5+6+7+8+9+10'.split('+')
['1','2','3','4','5','6','7','8','9','10']
strip()
去除两侧多余显示字符(默认去除空格)
>>> ' this is test!!! '.strip()
'!!!this is test!!!'
>>> 'this is test!!!'.strip('!')
'this is test'
lstrip()
去除开始多余显示字符(默认去除空格)
>>> '!!!this is test!!!'.lstrip('!')
'this is test!!!'
rstrip()
去除结束多余显示字符(默认去除空格)
>>> '!!!this is test!!!'.rstrip('!')
'!!!this is test'
format()
位置序列号格式化参数
>>> a = "可爱的{0},最喜欢在{1},{2}!!!"
>>> b = a.format("小猪","河边","抓泥鳅")
>>> print(b)
可爱的小猪,最喜欢在河边,抓泥鳅!!!
字符串填充位置调整
字符串居中,靠左,靠右
test = "字符"
v1 = test.center(20,"*")
print(v1)
v2 = test.ljust(20,"*")
print(v2)
v3 = test.rjust(20,"*")
print(v3)
*********字符*********
字符******************
******************字符
expandtabs()
制表符
>>> a = "user\tenail\tpasswd\nxiaoming\t1234@test.com\t123"
>>> print(a.expandtabs(20))
user enail passwd
xiaoming 1234@test.com 123
去重
x=[1,2,3,1]
print(list(set(x)))