字符串内置函数
s.upper()
s.lower()
s.swapcase()
s.title()
s.capitalize()
s.isalnum()
s.isalpha()
s.isdigit()
s.isspace()
s.islower()
s.isupper()
连接函数join
>>> s1, s2 = 'bhy', 'tql'
>>> ''.join(s1)
'bhy'
>>> ''.join([s1, s2])
'bhytql'
>>> '-'.join([s1, s2, s1, s2])
'bhy-tql-bhy-tql'
>>> ' '.join(s1)
'b h y'
>>> '*'.join(s2)
't*q*l'
>>> s1.join(s2)
'tbhyqbhyl'
>>> s2.join(s1)
'btqlhtqly'
>>> '*'.join(('b', 'h', 'y', 't', 'ql'))
'b*h*y*t*ql'
对齐
>>> s = 'bhytql'
>>> s.center(20)
' bhytql '
>>> s.ljust(20)
'bhytql '
>>> s.rjust(5)
'bhytql'
>>> s.center(20, '=')
'=======bhytql======='
>>> s.center(20, 'ha')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
s.center(20, 'ha')
TypeError: The fill character must be exactly one character long
格式输出
%c %d %s %b %o %x %%
%08.2f
%-50.2s
消减
strip(), lstrip(), rstrip()
参数给出删除集合,默认为空格
>>> x = 'xxyyxyxyxyxyyxbhy'
>>> x.strip('xy')
'bh'
查找
find(), rfind(): 查找一个字符串在另一个字符串指定范围中位置,找不到返回-1
index(), rindex(): 查找一个字符串在另一个字符串指定范围中位置,找不到抛出异常
count(): 一个字符串在另一个字符串
替换
- 直接替换
>>> s = 'bhytql'
>>> s.replace('bhy', 'wqh')
'wqhtql'
- 按映射表转换
>>> table = str.maketrans('bhy', 'wqh')
>>> s = 'abhewuboewiywdyya'
>>> s.translate(table)
'awqewuwoewihwdhha'
分割
split(), rsplit(): 按指定字符分隔,默认空格,可指定次数,无返回值
partition(), rpartition(): 按指定字符分割,默认为空格,返回一个三元组