40个Python的字符串内建函数(包含用例)

235 阅读6分钟

1、capitalize()

将字符串的第一个字母变成大写,其他字母变小写。

s1="hello world"
print(s1.capitalize())
Hello world

2、center(width,fillchar)

返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。

s1="hello world"
print(s1.center(20,'*'))
****hello world*****

3、count(str,beg=0,end=len(string))

返回 str 在 string 里面出现的次数,如果指定 beg 或者 end,则返回指定范围内 str 出现的次数

print(s1.count('o'))
print(s1.count('o',6,11))
2
1

4、encode(encoding=“”,errors=“”)

以 encoding 指定的编码格式编码字符串,如果出错默认报​ValueError​异常,除非 errors 指定的是’ignore’或者’replace’

#!/usr/bin/python3

str = "W3Cschool教程";
str_utf8 = str.encode("UTF-8")
str_gbk = str.encode("GBK")

print(str)

print("UTF-8 编码:", str_utf8)
print("GBK 编码:", str_gbk)

print("UTF-8 解码:", str_utf8.decode('UTF-8','strict'))
print("GBK 解码:", str_gbk.decode('GBK','strict'))
W3Cschool教程
UTF-8 编码: b'\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'
GBK 编码: b'\xb2\xcb\xc4\xf1\xbd\xcc\xb3\xcc'
UTF-8 解码: W3Cschool教程
GBK 解码: W3Cschool教程

5、bytes.decode(encoding=“”,errors=“”)

Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。
例4给出

6、endswith(suffix,beg=0,end=len(string))

检查字符串是否以指定的字符串结束,如果指定了beg 或 end 则检查指定的范围内是否以指定的字符串结束,如果是,返回 True,否则返回 False.

print(s1.endswith('d'))
print(s1.endswith('d',1,10))
True
False

7、expandtabs()

把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。

#!/usr/bin/python3

str = "this is\tstring example....wow!!!"

print ("原始字符串: " + str)
print ("替换 \\t 符号: " +  str.expandtabs())
print ("使用16个空格替换 \\t 符号: " +  str.expandtabs(16))
原始字符串: this is     string example....wow!!!
替换 \t 符号: this is string example....wow!!!
使用16个空格替换 \t 符号: this is         string example....wow!!!

8、find(str,beg=0,end=len(string))

检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含,返回开始的索引值,否则返回-1。

print(s1.find('lo'))
print(s1.find('lo',5,))
3
-1

9、index(str,beg=0,end=len(string))

跟find()方法一样,只不过如果str不在字符串中会报一个异常

print(s1.index('a'))
ValueError: substring not found

10、isalnum()

如果字符串至少有一个字符并且所有字符都是字母或数字(不能有空格)则返回 True,否则返回 False。

print(s1.isalnum())
False

11、isalpha()

如果字符串至少有一个字符并且所有字符都是字母或中文字则返回 True, 否则返回 False。

12、isdigit()

如果字符串只包含数字则返回 True 否则返回 False。

13、islower()

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False。

14、isnumeric()

如果字符串中只包含数字字符,则返回 True,否则返回 False。

s2='12345'
print(s2.isnumeric())

True

15、isspace()

如果字符串中只包含空白,则返回 True,否则返回 False。

16、istitle()

如果字符串是标题化的(见 title())则返回 True,否则返回 False。

17、isupper()

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False。

18、join(seq)

以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串。

#!/usr/bin/python3

s1 = "-"
s2 = ""
seq = ("w", "3", "c", "s", "c", "h","o","o","l") # 字符串序列
print (s1.join( seq ))
print (s2.join( seq ))

w-3-c-s-c-h-o-o-l
w3cschool

19、len(string)

返回字符串长度

20、ljust(width[, fillchar])

返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。

#!/usr/bin/python3

str = "W3CSchool example....wow!!!"

print (str.ljust(50, '*'))

W3CSchool example....wow!!!**************************

21、lower()

转换字符串中所有大写字符为小写

22、lstrip()

截掉字符串左边的空格或指定字符

#!/usr/bin/python3

str = "     this is string example....wow!!!     ";
print( str.lstrip() );
str = "88888888this is string example....wow!!!8888888";
print( str.lstrip('8') );

this is string example....wow!!!     
this is string example....wow!!!8888888

23、maketrans(intab, outtab)

创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。

#!/usr/bin/python3

intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)

str = "this is string example....wow!!!"
print (str.translate(trantab))

th3s 3s str3ng 2x1mpl2....w4w!!!

24、max(str)

返回字符串 str 中最大的字母

25、min(str)

返回字符串 str 中最小的字母

26、replace(old, new [, max])

把 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次。

s4='hello world,hello python'
print(s4.replace('he','my'))
print(s4.replace('l','y',2))

myllo world,myllo python
heyyo world,hello python

27、rfind(str, beg=0,end=len(string))

类似于 find()函数,不过是从右边开始查找,返回字符串最后一次出现的位置,如果没有匹配项则返回-1。

#!/usr/bin/python3

str1 = "this is really a string example....wow!!!"
str2 = "is"

print (str1.rfind(str2))

print (str1.rfind(str2, 0, 10))
print (str1.rfind(str2, 10, 0))

print (str1.find(str2))
print (str1.find(str2, 0, 10))
print (str1.find(str2, 10, 0))

5
5
-1
2
2
-1

28、rindex( str, beg=0, end=len(string))

类似于 index(),不过是从右边开始。

29、rjust(width,[, fillchar])

返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串。

30、rstrip()

删除字符串末尾的(右边的)空格或指定字符。

31、split(str=“”, num=string.count(str))

以 str 为分隔符(默认为空格)截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串

#!/usr/bin/python3

str = "this is string example....wow!!!"
print (str.split( ))
print (str.split('i',1))
print (str.split('w'))

['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']

32、splitlines([keepends])

按照行(‘\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

#!/usr/bin/python3

str = "this is \nstring example....\nwow!!!"
print (str.splitlines( ))

['this is ', 'string example....', 'wow!!!']

33、startswith(substr, beg=0,end=len(string))

检查字符串是否是以指定子字符串 substr 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。

34、strip([chars])

在字符串上执行 lstrip()和 rstrip()

35、swapcase()

将字符串中大写转换为小写,小写转换为大写

36、title()

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

#!/usr/bin/python

str = "this is string example from youj....wow!!!"
print (str.title())

This Is String Example From W3CSchool....Wow!!!

37、translate(table, deletechars=“”)

根据 str 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中
同例23

38、upper()

转换字符串中的小写字母为大写

39、zfill (width)

返回长度为 width 的字符串,原字符串右对齐,前面填充0

#!/usr/bin/python3

str = "this is string example from youj....wow!!!"
print ("str.zfill : ",str.zfill(40))
print ("str.zfill : ",str.zfill(50))

str.zfill :  this is string example from youj....wow!!!
str.zfill :  000000this is string example from youj....wow!!!

40、isdecimal()

检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。

#!/usr/bin/python3

str = "youj2016"
print (str.isdecimal())

str = "23443434"
print (str.isdecimal())

False
True