Python3中字符串内置函数

Python3中字符串内置函数

str.capitalize()第一个字母改为大写

返回一个字符串,并将字符串第一个字母改为大写

>>>'aa'.capitalize()
Aa

str.casefold()将大写转为小写

将大写转为小写,类似于lower()

区别在于lower只能转换英文字母A-Z

casefold可以转换除汉语以外的其他有大小写的字符

>>> "Python".casefold()
'python'
>>> 'Δ'.casefold()
'δ'
>>> '阿斯蒂芬Δ'.casefold()
'阿斯蒂芬δ'
>>>

str.center(width[, fillchar])填充字符串

返回一个长度为width的字符串,如果width小于或等于str的长度返回原字符串,否则将str放在字符串的中间两边用fillchar填充,fillchar默认为空格

>>>'ss'.center(10)
'    ss    '
>>>'ss'.center(10, '-')
'----ss----'
>>>'ss'.center(1, '-')
'ss'
>>>'ss'.center(3, '-')
'-ss'

str.count(sub[, start[, end]])包含字符串sub的个数

返回str中包含字符串sub的个数,startend分别为开始查找和结束匹配的位置

>>>'hello world'.count('l')
3
>>>'hello world'.count('l', 6)
1
>>>'hello world'.count('l', 2, 4)
2

str.endswith(suffix[, start[, end]])字符串是否以suffix结尾

判断字符串是否以suffix结尾,startend分别为开始查找和结束匹配的位置

>>>'hello world'.endswith('w')
False
>>>'hello world'.endswith('d')
True
>>>'hello world'.endswith('d', 3 ,6)
False
>>>'hello world'.endswith(' ', 3 ,6)
True

str.expandtabs(tabsize=8)替换制表符(\t)

将字符串中的制表符(\t)用一个或多个空格替换

>>>'a\tbbb\tcccc\tde\t'.expandtabs(4) 
'a   bbb cccc    de  ' # a后面为3个空格,bbb后面为1个空格,cccc后面为1个空格,de后面为2个空格
# 将参数设置2
>>>'a\tbbb\tcccc\tde\t'.expandtabs(2) 
'a bbb cccc  de  ' # a后面为1个空格,bbb后面为1个空格,cccc后面为2个空格,de后面为2个空格

str.find(sub[, start[, end]])返回sub在字符串中的位置

返回sub在字符串中的位置,startend分别为开始查找和结束匹配的位置

>>> 'Python'.find('Py')
0
>>> 'Python'.find('y')
1
>>> 'Python'.find('aa')
-1

str.format(*args, **kwargs)格式化字符串

格式化字符串

>>> '{0} + {1} = {2}'.format(1,2,1+2)
'1 + 2 = 3'

str.index(sub[, start[, end]])返回sub在字符串中的位置

find()类似,返回sub在字符串中的位置,startend分别为开始查找和结束匹配的位置

如果sub不存在会导致ValueError异常

>>> 'Python'.index('Py')
0
>>> 'Python'.index('cc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

str.isalnum()字符串是否全是数字和文字

字符串是否全是数字和文字

>>> 'aa'.isalnum()
True
>>> '11'.isalnum()
True
>>> '1.1'.isalnum()
False
>>> '哈喽'.isalnum()
True
>>> '哈喽!'.isalnum()
False

str.isalpha()字符串是否全是文字

字符串是否全是文字

>>> 'aa'.isalpha()
True
>>> '1'.isalpha()
False
>>> '哈利'.isalpha()
True
>>> '哈利!'.isalpha()
False

str.isascii()字符串中的字符是否全是ASCII

字符串中的字符是否全是ASCII

>>> 'python'.isascii()
True
>>> '123456'.isascii()
True
>>> '!@#$%^&*()'.isascii()
True
>>> '哈喽'.isascii()
False

str.isidentifier()判断字符串是否为合法的python标识符

判断字符串是否为合法的python标识符

>>> 'a'.isidentifier()
True
>>> 'b'.isidentifier()
True
>>> '!'.isidentifier()
False
>>> '哈喽'.isidentifier()
True
>>> '_asdf_asdf'.isidentifier()
True

str.islower()是否全为小写字母

是否全为小写字母

>>> 'aa'.islower()
True
>>> 'aAa'.islower()
False
>>> '!'.islower()
False
>>> '123'.islower()
False

str.isprintable()是否可打印

是否可打印,即是否包含控制字符

ascii码中0-31以及127等33个为控制字符

>>> print('\t'.isprintable())
False
>>> print('\n'.isprintable())
False
>>> print('\r'.isprintable())
False
>>> print(' '.isprintable())
True
>>> print('\b'.isprintable())
False
>>> print('\\b'.isprintable())
True

str.isspace()字符串中的字符是否全为空白

字符串中的字符是否全为空白

>>> ' '.isspace()
True
>>> ''.isspace()
False
>>> '\t'.isspace()
True
>>> '\n'.isspace()
True
>>> 'abc\n'.isspace()
False

str.istitle()是否为标题

字面意思为是否为标题,意思就是字符串是否包含大写字母,并且大写字母前面不能有其他大写字母和小写字母

False
>>> 'Python'.istitle()
True
>>> 'python'.istitle()
False
>>> '1Python'.istitle()
True
>>> 'pYthon'.istitle()
False
>>> '123,!@,$Python'.istitle()
True

str.isupper()是否全为大写

字符串中的字母是否全为大写

>>> 'Python'.isupper()
False
>>> 'python'.isupper()
False
>>> 'PYTHON'.isupper()
True
>>> ''.isupper()
False
>>> '123PYTHON'.isupper()
True
>>> '123PYTHON!'.isupper()
True

str.join(iterable)分割对象

传入一个可迭代的对象将对象的各个元素以str分割

>>> '.'.join(['127','0','0','1'])
'127.0.0.1'

str.ljust(width[, fillchar])填充字符串

如果str的长度比width短,则在str的右侧补充fillchar,直到长度等于widthfillchar默认为空格

>>> '100'.ljust(6,'0')
'100000'

str.lower()大写字母全部改成小写字母

将字符串中的大写字母全部改成小写字母并返回

>>> 'Python'.lower()
'python'

str.lstrip([chars])移除字符

str左侧开始遍历,如果遍历的字符在chars中,则移除,知道遍历的字符不在chars中,chars默认为空白符(’\t’,’\n’,’ '等)

>>> '\t \n hello'.lstrip()
'hello'
>>> '\t  hello'.lstrip()
'hello'
>>> '  hello'.lstrip('l')
'  hello'
>>> 'l  hello'.lstrip('l')
'  hello'
>>> 'l  hello'.lstrip('l ')
'hello'

str.partition(sep)字符串分割

从左向右查找字符串sep,并在找到的位置使用sep将字符串分割为一个包含三个字符串的元组

>>> '1122332211'.partition('11')
('', '11', '22332211')
>>> '1122332211'.partition('22')
('11', '22', '332211')
>>> '1122332211'.partition('44')
('1122332211', '', '')

str.removeprefix(prefix)移除prefix并返回新的字符串

如果strprefix开头,则移除prefix并返回新的字符串,如果开头不是prefix,则返回原字符串

>>> 'http://baidu.com'.removeprefix('http://')
'baidu.com'
>>> 'http://baidu.com'.removeprefix('//')
'http://baidu.com'

str.removesuffix(suffix)移除suffix并返回新的字符串

如果strsuffix结尾,则移除suffix并返回新的字符串,如果结尾不是suffix,则返回原字符串

>>> 'http://baidu.com'.removesuffix('.com')
'http://baidu'
>>> 'http://baidu.com'.removesuffix('baidu')
'http://baidu.com'

str.replace(old, new[, count])替换字符串

将字符串中old替换为newcount为可选参数,表示要替换的个数,默认全部替换

>>> 'www.baidu.com'.replace('w', 'W')
'WWW.baidu.com'
>>> 'www.baidu.com'.replace('w', 'W',1)
'Www.baidu.com'
>>> 'www.baidu.com'.replace('w', 'W',2)
'WWw.baidu.com'
>>> 'www.baidu.com'.replace('w', 'W',3)
'WWW.baidu.com'

str.rfind(sub[, start[, end]])右向左查找字符串sub

从右向左在str中查找字符串sub,并返回查找到的第一个下标,startend为查找的下标范围

如果没有查找到返回-1

>>> 'hello world'.rfind('l')
9
>>> 'hello world'.rfind('l', 1, 4)
3
>>> 'hello world'.rfind('f')
-1

str.rjust(width[, fillchar])填充字符串

如果str的长度比width短,则在str的左侧补充fillchar,直到长度等于widthfillchar默认为空格

>>> '100'.rjust(6, '0')
'000100'

str.rpartition(sep)字符串分割

从右向左查找字符串sep,并在找到的位置使用sep将字符串分割为一个包含三个字符串的元组

>>> '1122332211'.rpartition('11')
('11223322', '11', '')
>>> '1122332211'.rpartition('22')
('112233', '22', '11')
>>> '1122332211'.rpartition('44')
('', '', '1122332211')

str.rsplit(sep=None, maxsplit=-1)字符串分割

从右开始查找sep,使用字符串sepstr分割为一个字符串列表,最多执行maxsplit次分割,默认全部分割

>>> '1122332211'.rsplit('22')
['11', '33', '11']
>>> '1122332211'.rsplit('22',1)
['112233', '11']
>>> '  1122 33  22  11  '.rsplit()
['1122', '33', '22', '11']

str.rstrip([chars])移除字符

str右侧开始遍历,如果遍历的字符在chars中,则移除,知道遍历的字符不在chars中,chars默认为空白符(’\t’,’\n’,’ '等)

>>> 'hello \t \n  '.rstrip()
'hello'
>>> 'hello \t \n  '.rstrip(' ')
'hello \t \n'

### str.split(sep=None, maxsplit=-1)分割字符串

从左开始查找sep,使用字符串sepstr分割为一个字符串列表,最多执行maxsplit次分割,默认全部分割

>>> '  1122 33  22  11  '.split('22',1)
['  11', ' 33  22  11  ']
>>> '  1122 33  22  11  '.split('22')
['  11', ' 33  ', '  11  ']
>>> '  1122 33  22  11  '.split()
['1122', '33', '22', '11']

### str.splitlines([keepends])分割字符串

按行分割字符串,keepends是否显示行尾字符

>>> '11\n22\n33\n'.splitlines()
['11', '22', '33']
>>> '11\n22\n33\n'.splitlines(True)
['11\n', '22\n', '33\n']
>>> '11\n22\t33\n'.splitlines(True)
['11\n', '22\t33\n']
>>> '11\n22\v33\n'.splitlines(True)
['11\n', '22\x0b', '33\n']
>>> '11\n\n22\r\b33\n'.splitlines(True)
['11\n', '\n', '22\r', '\x0833\n']
>>> '11\n\n22\r\b33\n'.splitlines()
['11', '', '22', '\x0833']

str.startswith(prefix[, start[, end]])字符串是否以prefix开头

判断字符串是否以prefix开头,startend分别为开始查找和结束匹配的位置

>>> 'hello world'.startswith('h')
True
>>> 'hello world'.startswith('w')
False
>>> 'hello world'.startswith('w',6)
True
>>> 'hello world'.startswith('world',6,8)
False

str.strip([chars])移除字符

str左侧开始遍历,如果遍历的字符在chars中,则移除,知道遍历的字符不在chars中,chars默认为空白符(’\t’,’\n’,’ '等)

>>> ' \t \n hello'.strip()
'hello'
>>> ' \t \n hello'.strip(' ')
'\t \n hello'

str.swapcase()字符串中字母的大小写互换

将字符串中字母的大小写互换

>>> 'Python'.swapcase()
'pYTHON'
>>> 'Python'.swapcase().swapcase()
'Python'

str.title()字符串中单词的第一个字母改为大写其余的改为小写

将字符串中单词的第一个字母改为大写其余的改为小写

>>> 'hello world'.title()
'Hello World'
>>> 'hello world 3.9PYTHON'.title()
'Hello World 3.9Python

str.upper()小写字母全部改成大写字母

将字符串中的小写字母全部改成大写字母并返回

>>> 'python'.upper()
'PYTHON'

str.zfill(width)字符串左边补充0

将字符串左边补充‘0’,直到str的长度等于width,可以自动识别数字的±符号,但只能识别第一个符号

>>> 'aa'.zfill(6)
'0000aa'
>>> '11'.zfill(6)
'000011'
>>> '-11'.zfill(6)
'-00011'
>>> '+11'.zfill(6)
'+00011'
>>> '++11'.zfill(6)
'+00+11'

str.maketrans(x[, y[, z]])制作字符串的映射表

str.translate(table)换字符串

maketranstranslate需要配合使用

maketrans用于制作字符串的映射表

translate根据maketrans制作的映射表替换字符串

maketrans可以传入三个参数,

当只有一个参数时,这个参数必须是一个字典,并且字典的key字符串长度必须为1

当有两个参数时,两个字符串长度必须一样,字符一一对应

当有三个参数时,两个字符串长度必须一样,字符一一对应,第三个字符串为需要删除的字符列表

>>> mt = str.maketrans({'o':'12'}) # 字母o映射字符串'12'
>>> 'python'.translate(mt) # 将字符串中的字母o替换为字符串'12'
'pyth12n'
>>> mt = str.maketrans('ol','-+', 'hw') # 字母o对应-,字母l对应+,字母h和w会被删除
>>> 'hello world'.translate(mt) # o被-替换,l被+替换,删除h和w
'e++- -r+d'
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bdawn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值