python string操作的函数方法(1)

Slicing

slicing函數切片,按照一定條件從列表或者元組中取出部分元素(比如特定範圍,索引,分割值)

a = '   hello '
a = a[3:8]
print(a)
#輸出:hello

strip()

strip函数方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。 在使用该方法时,默认去除空格或换行符,但是可以指定字符,比如去除$号 或者剥离所含值的所有组合,比如下列示例百度网址

b = '   hello   '.strip()
print(b)
#輸出:hello

b = '$$$hello$$$'.strip()
print(b)
#輸出:$$$hello$$$

b = '$$$hello$$$'.strip('$')
print(b)
#輸出:hello

b = 'www.baidu.com'.strip('cmow.')
print(b)
#輸出:baidu

lstrip()

该函数方法用来移除字符串左侧指定的字符(默认为空格或换行符)或字符序列。使用方法如上所示

rstrip()

该函数方法用来移除字符串右侧指定的字符(默认为空格或换行符)或字符序列。使用方法如上所示

removeprefix()

这个函数方法需要python version>= 3.9 才可以使用,用来移除前缀的函数。与strip()相比,并不会把字符串中的字符逐个匹配

c = 'ctexthuang: First blood!'.removeprefix('ctexthuang: ')
print(c)
#输出:First blood!

removesuffix()

同样的需要python version >= 3.9,用来移除后缀的函数。

c = 'ctexthuang: First blood!'.removesuffix('First blood!')
print(c)
#输出:ctexthuang:

replace()

该函数用于把字符串中的内容替换成指定的内容。

d = '你 好 呀'.replace(' ', '-')
print(d)
#輸出:你-好-呀

re.sub()

re是正则的表达式,sub是substitute表示替换。 和replace()做对比,使用re.sub()进行替换操作,确实更高级点。

import re
e = "你 好 呀!"
eCopy = re.sub("\s+", "-", e)
print(eCopy)
#輸出:你-好-呀!

split()

對字符串做分割處理,最終的結果是一個列表。当不指定分隔符时,默认按空格分隔。並且,还可以指定字符串的分隔次数。

f = '你 好 呀'.split()
print(f)
#輸出:['你', '好', '呀']

f = '你 好 呀'.split(' ',maxsplit=1)
print(f)
#輸出:['你', '好 呀']

rsplit()

从右侧开始对字符串进行分隔。

f = '你 好 呀'.rsplit(' ',maxsplit=1)
print(f)
#輸出:['你 好', '呀']

join()

string.join(seq)。以string作為分隔符,将列表中所有的元素合并为一个新的字符串。

list = ['你', '好', '世', '界']
g = '-'.join(list)
print(g)
#輸出:你-好-世-界
tag(s): none
show comments · back · home
Edit with Markdown
召唤看板娘