python字符串方法

发布时间 2024-01-13 21:05:27作者: jl1771

字符串方法比较多,其中很多方法都是从模块string那里“继承”而来的。

虽然字符串方法完全盖住了模块string的风头,但这个模块包含一些字符串没有的常量和函数。下面就是模块string中几个很有的常量。

  • string.digits:包含数字0~9的字符串。
  • string.ascii_letters:包含所有ASCII字母(大写和小写)的字符串。
  • string.ascii_uppercase:包含所有大写ASCII字母的字符串。
  • string.ascii_lowercase:包含所有小写ASCII字母的字符串。
  • string.printable:包含所有可打印的ASCII字符的字符串。
  • string.punctuation:包含所有可打印的标点字符的字符串。

然说的是ASCII字符,但值实际上是未解码的Unicode字符串。

1 center

方法center通过在两边添加填充字符(默认为空格)让字符串居中。

>>> 'abc'.center(10)
'   abc    '
>>> 'abc'.center(10,'*')
'***abc****'

相关函数ljust、rjust、zfill。

2 find

方法find在字符串中查找子串,如果找到就返回字串的第一个字符的索引,否则返回-1。

>>> 'a string containing all ASCII whitespace'.find('all')
20
>>> str='a string containing all ASCII whitespace'
>>> str.find('con')
9
>>> str.find('a ')
0
>>> str.find('ace')
37
>>> str.find('2')
-1

# 可以指定起点和终点值(第二个和第三个参数)
>>> x='abc 123 456 abc'
>>> x.find('abc')
0
>>> x.find('abc',1)
12
>>> x.find('123')
4
>>> x.find('123',1)
4
>>> x.find('123',1,4)
-1

相关函数:rfind、index、rindex、count、startwith、endwith。

3 join

join是一个非常重要的字符串方法,其作用与split相反,用于合并序列的元素。

>>> seq=[1,2,3,4,5]
>>> sep='+'
>>> sep.join(seq) #不能合并数字列表
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
>>> seq=['1','2','3','4','5']
>>> sep.join(seq) #合并字符列表
'1+2+3+4+5'

>>> dir = '','usr','bin','env'
>>> '/'.join(dir)
'/usr/bin/env'
>>> print('C:'+'\\'.join(dir))
C:\usr\bin\env

相关函数:split。

4 lower

方法lower返回字符串的小写版本

>>> a='Life is short, You need Python'
>>> a.lower()
'life is short, you need python'

相关函数:islower、istitle、isupper、translate。

5 replace

方法replace将指定字符串都替换为另一个字符串,并返回替换后的结果。

>>> 'Life is short, You need Python'.replace('You','We')
'Life is short, We need Python'

相关函数:itranslate。

6 split

split是一个非常重要的字符串方法,其作用与join相反,用于将字符串拆分为序列。

>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']

注意,如果没有指定分隔符,将默认在单个或多个连续的空白字符(空格、制表符、换行符等)处进行拆分。

7 strip

方法strip将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果。

>>> '  Life is short, You need Python  '.strip()
'Life is short, You need Python'
# 可以在字符串中指定要删除那些字符
>>> ' **  Life is short, You need Python  *!*'.strip('*! ')
'Life is short, You need Python'