Python_字符串方法
1. 方法
注:isdigit、isdecimal和isnumeric的区别可以参考:https://www.runoob.com/python/att-string-isnumeric.html
2. 例子
(1)查找
>>> s = ‘hello worLd‘ >>> s.find(‘l‘) 2 >>> s.index(‘l‘) 2 >>> s.find(‘a‘) -1 >>> s.index(‘a‘) Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> s.index(‘a‘) ValueError: substring not found >>> s.find(‘l‘,6) # 不考虑大小写 -1
(2)替换
>>> s = ‘hello worLd‘ >>> s.replace(‘l‘,‘*‘) # 考虑大小写 ‘he**o worLd‘ >>> table = str.maketrans(‘l‘,‘*‘) >>> s.translate(table) ‘he**o worLd‘
(3)切片
>>> s = ‘hello\nworld\nhello\nBunny‘ >>> s.split(‘\n‘) [‘hello‘, ‘world‘, ‘hello‘, ‘Bunny‘] >>> s.partition(‘\n‘) (‘hello‘, ‘\n‘, ‘world\nhello\nBunny‘) >>> s.splitlines() [‘hello‘, ‘world‘, ‘hello‘, ‘Bunny‘]
(4)填充
>>> s = ‘hello world‘ >>> s.ljust(20,‘0‘) ‘hello world000000000‘ >>> s.zfill(20) ‘000000000hello world‘
1 >>> s = ‘hello\nworld\nhello\nBunny‘ 2 >>> ‘,‘.join(s.splitlines()) 3 ‘hello,world,hello,Bunny‘
(5)删除
1 >>> s = ‘\thello world \n‘ 2 >>> s.strip() 3 ‘hello world‘
(6)大小写
>>> s = ‘HEllo worLd‘ >>> s.lower() ‘hello world‘ >>> s.upper() ‘HELLO WORLD‘ >>> s.capitalize() ‘Hello world‘ >>> s.title() ‘Hello World‘ >>> s.swapcase() ‘heLLO WORlD‘
(7)计数
1 >>> s = ‘hello worLd‘ 2 >>> s.count(‘l‘) # 考虑大小写 3 2
(8)判断
>>> num1 = ‘Ⅳ‘ >>> num1.isdigit() False >>> num1.isdecimal() False >>> num1.isnumeric() True >>> num2 = ‘万‘ >>> num2.isdigit() False >>> num2.isdecimal() False >>> num2.isnumeric() True
相关推荐
huavhuahua 2020-11-20
weiiron 2020-11-16
cakecc00 2020-11-15
千锋 2020-11-15
JakobHu 2020-11-14
guangcheng 2020-11-13
xirongxudlut 2020-11-10
solarLan 2020-11-09
pythonxuexi 2020-11-08
文山羊 2020-11-07
susmote 2020-11-07
wuShiJingZuo 2020-11-05
Pythonjeff远 2020-11-06
jacktangj 2020-11-04
lousir 2020-11-04
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17