Python字符串处理函数

字符串测试函数
函数名 什么情况下返回True
s.endswith(t) s以字符串t结尾
s.startswith(t) s以字符串t打头
s.isalnum() s只包含字母或数字
s.isalpha() s只包含字母
s.isdecimal() s只包含表示十进制数字的字符
s.isdigit() s只包含数字字符
s.isidentifier() s只包含合法的标识符
s.islower() s只包含小写字母
s.isnumeric() s只包含数字
s.isprintable() s只包含可打印的字符
s.isspace() s只包含空白字符
s.istitle() s是个大小写符合头衔要求(title-case)的字符串
s.isupper() s只包含大写字母

t in s

s包含字符串t

检测字符串是否为特定格式的函数。它们只返回True或False,因此也叫布尔函数。

Python title() 方法返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写。

字符串搜索函数
函数名 返回值
s.find(t) 如果在s中没有找到字符串t,返回-1;否则,返回t在s中的起始位置
s.rfind(t) 与find相同,但是从右往左搜索
s.index(t) 与find相同,但如果在s中找不到t,则引发ValueError异常
s.rindex(t) 与index相同,但是从右往左搜索
改变大小写的函数
函数名 返回的字符串
s.capitalize() 将s的首字母改为大写
s.lower() 将s的所有字母都小写
s.upper() 将s的所有字母都大写
s.swapcase() 将s的小写字母改大写,大写字母改小写
s.title() 将s改的符合头衔要求
设置字符串格式的函数
函数名 返回的字符串
s.center(n,ch) 将s扩展为包含n个字符的字符串,其中s位于中央,两边用字符ch填充
s.ljust(n,ch) 将s扩展为包含n个字符的字符串,其中s位于左边,右边用字符ch填充
s.rjust(n,ch) 将s扩展为包含n个字符的字符串,其中s位于右边,左边用字符ch填充
s.format(vars) 用vars代替字符串s中用{}抱起来的内容,直接上代码
>>> '{0} likes {1}'.format('Jack','apple')
'Jack likes apple'

>>> '{who} likes {fruit}'.format(who='Jack',fruit='apple')
'Jack likes apple'

>>> '{0} likes {1}'.format(1='Jack',0='apple')
  File "<stdin>", line 1
SyntaxError: keyword can't be an expression
 
>>> '{who} likes {fruit}'.format('Jack','apple')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'who'
字符串剥除函数
函数名 返回的字符串
s.strip(ch) 从s开头和末尾删除字符串ch中包含的字符
s.lstrip(ch) 从s开头(左端)删除字符串ch中包含的字符
s.rstrip(ch) 从s末尾(右端)删除字符串ch中包含的字符

说那么多干啥,直接上代码

>>> a="aabcacb1111acbba"

>>> print(a.strip("a"))#只删除开头和结尾的‘a’
bcacb1111acbb

>>> print(a.strip("ab"))#删除开头和结尾的‘a’和‘b’
cacb1111ac
>>> print(a.strip("ba"))
cacb1111ac

>>> print(a.strip("abc"))
1111
>>> print(a.strip("acb"))
1111
字符串拆分函数
函数名 返回的字符串
s.partition(sep) 将s拆分为三个字符串——head、sep和tail,其中head是sep之前的字符串,tail是sep之后的
s.rpartition(sep) 与partition相同,不过是从s的右端开始搜索sep
s.split(sep,maxsplit) 以sep为分隔符,将s划分为maxsplit个子串,并返回由这些子串组成的列表
s.rsplit(sep,maxsplit) 与split相同,不过是从s的右端开始搜索sep
s.splitlines() 返回一个由s中各行组成的列表
>>> a='abc1111cba'

>>> a.partition('b')
('a', 'b', 'c1111cba')
>>> a.rpartition('b')
('abc1111c', 'b', 'a')

>>> a.split('b',1)
['a', 'c1111cba']
>>> a.split('b',10)#请注意这种情况,maxsplit大于能划分的段数,这时,就只好返回最大段数
['a', 'c1111c', 'a']
>>> a.rsplit('b',1)
['abc1111c', 'a']

>>> a.splitlines()
['abc1111cba']
字符串替换函数
函数名 返回的字符串
s.replace(old ,new [, count ])

将s中的[前count个]old替换为new

s.expandtabs(n) 将s中的每个制表符替换为n个空格
>>> a='abcabcacbaaabc'

>>> a.replace('abc','1')
'11acbaa1'
>>> a.replace('abc','1',2)
'11acbaaabc'
其他函数
函数名 返回的字符串
s.count(t) t在s中出现的次数
s.encode() 设置s的编码
s.join(seq) 使用s将seq中的字符串连接成一个字符串
s.maketrans(old,new) 创建一个转换表,用于将old中的字符改为new中相应的字符:请注意,s可以是任何字符串,它不影响返回的转换表
s.translate(table) 使用指定的转换表(使用makestrans创建的)对s中的字符进行替换
s.zfill(width) 在s左边添加足够多的0,让字符串的长度为width

自助方法:

天行健,裙子以自强不息;地势坤,君子以厚德载物

Q:如果想知道Python有哪些字符串相关的函数,如何自助呢?

>>> dir("abc")
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
 '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',
 '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__',
 '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', 
 '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 
 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 
 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 
 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 
 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 
 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 
 'translate', 'upper', 'zfill']

Q:如果想知道上面的capitalize函数的使用方法,如何自助呢?

>>> 'abc'.capitalize.__doc__
'S.capitalize() -> str\n\nReturn a capitalized version of S, i.e. make the first character\nhave upper case and the rest lower case.'

这信息也TMD长了吧。就不能换行,处理一下吗?

>>> print('abc'.capitalize.__doc__)
S.capitalize() -> str

Return a capitalized version of S, i.e. make the first character
have upper case and the rest lower case.

这要输入的也TMD多了吧!

>>> help('abc'.capitalize)
Help on built-in function capitalize:

capitalize(...) method of builtins.str instance
    S.capitalize() -> str
    
    Return a capitalized version of S, i.e. make the first character
    have upper case and the rest lower case.

 天天TMD,AB西、AB西的。让abc洗去吧

>>> help(''.capitalize)#这是两个连着的单引号
Help on built-in function capitalize:

capitalize(...) method of builtins.str instance
    S.capitalize() -> str
    
    Return a capitalized version of S, i.e. make the first character
    have upper case and the rest lower case.

                                                                                THE END

                                                                       THANKS FOR READING

猜你喜欢

转载自blog.csdn.net/qq_35629563/article/details/84304770