Python-5-字符串方法

center
>>> "The Middle by Jimmy Eat World".center(39)
'     The Middle by Jimmy Eat World     '
>>> "The Middle by Jimmy Eat World".center(39, "*")
'*****The Middle by Jimmy Eat World*****'
 
find
在字符串中查找子串,找到返回子串第一个字符索引,否则返回-
>>> 'With a moo-moo here, and a moo-moo there'.find('moo')
7
>>> title = "Monty Python's Flying Circus"
>>> title = "Monty Python's Flying Circus"
>>> title.find('Monty')
0
>>> title.find('Zirquss')
-1
成员资格检查in智能用于单个字符,而这个可以多个
可以指定起点和终点
>>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$', 1) # 只指定了起点
20
>>> subject.find('!!!')
16
>>> subject.find('!!!', 0, 16) # 同时指定了起点和终点
-1
起点和终点值指定的范围包含起点不包含终点,这是python的惯用做法
 
join
与split相反
>>> seq = [1, 2, 3, 4, 5]
>>> sep = '+'
>>> sep.join(seq) # 尝试合并一个数字列表
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: sequence item 0: expected string, int found
>>> seq = ['1', '2', '3', '4', '5']
>>> sep.join(seq) # 合并一个字符串列表
'1+2+3+4+5'
>>> dirs = '', 'usr', 'bin', 'env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print('C:' + '\\'.join(dirs))
C:\usr\bin\env
 
lower
返回小写版本
>>> 'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'
 
title
所有单词首字母大写
>>> "that's all folks".title()
"That'S All, Folks"
 
replace
将指定子串都替换为另一个字符串,并返回替换后的结果
>>> 'This is a test'.replace('is', 'eez')
'Theez eez a test'
 
split
与join相反,将字符串拆分为序列
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>> 'Using the default'.split()
['Using', 'the', 'default']
 
strip
将字符串的开头和末尾的空白删除,并返回删除后的结果
>>> ' internal whitespace is kept '.strip()
'internal whitespace is kept'
 
translate
使用前要先创建一个转换表
>>> table = str.maketrans('cs', 'kz')
两个参数为两个长度相同的字符串,指定将第一个字符串中的每个字符都替换为第二个字符串中相应的字符
内部存储为unicode
>>> table
{115: 122, 99: 107}
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
第三个参数为指定要将那些字母删除
>>> table = str.maketrans('cs', 'kz', ' ')
>>> 'this is an incredible test'.translate(table)
'thizizaninkredibletezt'
 
判断字符串是否满足特定条件
是true,否则false
isalnum、 isalpha、 isdecimal、 isdigit、 isidentifier、 islower、 isnumeric、isprintable、 isspace、 istitle、 isupper
 
 
 
 
 
 
 
posted @ 2019-04-30 13:32  swefii  阅读(143)  评论(0编辑  收藏  举报