flowerCSDN 2020-03-06
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