1. 方法

  Python_字符串方法 Python

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

注:isdigit、isdecimalisnumeric的区别可以参考:https://www.runoob.com/python/att-string-isnumeric.html

 

2. 例子

(1)查找

 1 >>> s = 'hello worLd'
 2 >>> s.find('l')  3 2
 4 >>> s.index('l')  5 2
 6 >>> s.find('a')  7 -1
 8 >>> s.index('a')  9 Traceback (most recent call last): 10   File "<pyshell#4>", line 1, in <module>
11     s.index('a') 12 ValueError: substring not found 13 >>> s.find('l',6)    # 不考虑大小写
14 -1

(2)替换

1 >>> s = 'hello worLd'
2 >>> s.replace('l','*')    # 考虑大小写
3 'he**o worLd'
4 >>> table = str.maketrans('l','*') 5 >>> s.translate(table) 6 'he**o worLd'

(3)切片

1 >>> s = 'hello\nworld\nhello\nBunny'
2 >>> s.split('\n') 3 ['hello', 'world', 'hello', 'Bunny'] 4 >>> s.partition('\n') 5 ('hello', '\n', 'world\nhello\nBunny') 6 >>> s.splitlines() 7 ['hello', 'world', 'hello', 'Bunny']

(4)填充

1 >>> s = 'hello world'
2 >>> s.ljust(20,'0') 3 'hello world000000000'
4 >>> s.zfill(20) 5 '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)大小写

 1 >>> s = 'HEllo worLd'
 2 >>> s.lower()  3 'hello world'
 4 >>> s.upper()  5 'HELLO WORLD'
 6 >>> s.capitalize()  7 'Hello world'
 8 >>> s.title()  9 'Hello World'
10 >>> s.swapcase() 11 'heLLO WORlD'

(7)计数

1 >>> s = 'hello worLd'
2 >>> s.count('l')    # 考虑大小写
3 2

(8)判断

 1 >>> num1 = ''
 2 >>> num1.isdigit()  3 False  4 >>> num1.isdecimal()  5 False  6 >>> num1.isnumeric()  7 True  8 >>> num2 = ''
 9 >>> num2.isdigit() 10 False 11 >>> num2.isdecimal() 12 False 13 >>> num2.isnumeric() 14 True
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄