Python3的字符串内建函数

按照功能分类
转换类      
capitalize()      
expandtabs(tabsize=8)      
maketrans() translate(table, deletechars="")    
lower() upper() swapcase()  
replace(old, new [, max])      
title()      
判断类      
endswith(suffix, beg=0, end=len(string)) startswith(str, beg=0,end=len(string))    
isalpha()      
islower() isupper()    
isnumeric() isdigit() isalnum()  
isspace()      
istitle()      
裁剪类      
lstrip() rstrip() strip([chars])  
split(str="", num=string.count(str)) splitlines([keepends])    
填充类      
center(width, fillchar)      
join(seq)      
ljust(width[, fillchar]) rjust(width,[, fillchar])    
zfill (width)      
寻找统计类      
count(str, beg= 0,end=len(string))      
find(str, beg=0 end=len(string)) rfind(str, beg=0,end=len(string))    
index(str, beg=0, end=len(string)) rindex( str, beg=0, end=len(string))    
max(str) min(str)    
len(string)      
编码类      

encode(encoding='UTF-8',errors='strict')





序号 方法及描述
1

capitalize()

首字母大写

a='ab'
print(a.capitalize())
输出
Ab
2

center(width, fillchar)

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

a='ab'
print(a.center(10))
print(a.center(10,'*'))

输出
    ab    
****ab****
3

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

扫描二维码关注公众号,回复: 2162271 查看本文章

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

a='asasddfgghjas'
print(a.count('as'))        #a中出现'as'的次数      输出3
print(a.count('as',0,-1))   #a从第一个到倒数第二个出现'as'的次数       输出2
print(a.count('qwer'))      #a中出现'qwer'的次数      输出0
4

bytes.decode(encoding="utf-8", errors="strict")

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

5

encode(encoding='UTF-8',errors='strict')

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

encoding -- 要使用的编码,如: UTF-8。

errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

6

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

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

Str='Runoob example....wow!!!'
suffix='!!'
print (Str.endswith(suffix))
print (Str.endswith(suffix,20))
suffix='run'
print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))
7

expandtabs(tabsize=8)

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

a='123\t45'
print(a.expandtabs(8))
8

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

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

ps:返回的索引是相对于整个字符串的索引,无论是否切片

ps:返回的索引位置是找到的第一个位置

str1 = "Runoob example....wow!!!exam"
str2 = "exam"
print(str1.find(str2))          #返回7
print(str1.find(str2, 4))       #返回7
print(str1.find(str2, 10))      #返回24
print(str1.find(str2, 4, 10))   #返回-1
9

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

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

isalnum()

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

isalpha()

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

isdigit()

如果字符串不为空并且只包含数字则返回 True 否则返回 False
13

islower()

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

a='123'
print(a.islower())  #返回False
a='123a'
print(a.islower())  #返回True
a='123A'
print(a.islower())  #返回False
a='123aA'
print(a.islower())  #返回False
a=''
print(a.islower())  #返回False
14

isnumeric()

如果字符串中不为空并且只包含数字字符,则返回 True,否则返回 False
15

isspace()

如果字符串不为空并且只包含空白(空格),则返回 True,否则返回 False.
16

istitle()

方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。

17

isupper()

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

类似islower()

18

join(seq)

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

a='**'
b='test'
c='*'
d=('t','e','s','t')
d2=['a','f','g','h']
e=''
print(b.join(c)) #*
print(b.join(a)) #*test*
print(c.join(b)) #t*e*s*t
print(c.join(d)) #t*e*s*t 
print(e.join(d2))#afgh 类型字符串
19

len(string)

返回字符串长度

a='adsf'
print(len(a))       #4
print(a.__len__())  #4
20

ljust(width[, fillchar])

返回一个原字符串左对齐,并使用 fillchar 填充至长度 

width 的新字符串

fillchar 默认为空格

a='asdf'
print(a.ljust(10,'*'))  #asdf******
21

lower()

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

a='123asdfAB'
print(a.lower())    #123asdfab
22

lstrip()

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

ss1 = "     this is string example....wow!!!     "
ss2 = "88888888this is string example....wow!!!8888888"
print(ss1.lstrip())     #this is string example....wow!!! 
print(ss2.lstrip('8'))  #this is string example....wow!!!8888888
print(ss2)              #88888888this is string example....wow!!!8888888
23

maketrans()

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

两个字符串的长度必须相同,为一一对应的关系。

注:Python3.4已经没有string.maketrans()了,取而代之的是内建函数: bytearray.maketrans()、bytes.maketrans()、str.maketrans()

语法:

str.maketrans(intab, outtab)
intab -- 字符串中要替代的字符组成的字符串。

outtab -- 相应的映射字符的字符串。

intab='abcd'
outtab='1234'
c='sadfghh45321'
trantab=str.maketrans(intab,outtab)
print(c.translate(trantab))     #s14fghh45321
24

max(str)

返回字符串 str 中最大的字母。大小按照ascii表排序

a='abcdABCD'
b='123'
c='abcdABCD123'
print(max(a))   #d
print(min(a))   #A

print(max(b))   #3
print(min(b))   #1

print(max(c))   #d
print(min(c))   #1
25

min(str)

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

详见max(str)

26

replace(old, new [, max])

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

ss = "www.w3cschool.cc"
print(ss.replace('www','***'))  #***.w3cschool.cc
27

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

类似于 find()函数,不过是从右边开始查找.
28

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

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

rjust(width,[, fillchar])

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

rstrip()

类似lstrip,默认删除空格,有输出参数的时候,删除对应的参数
删除字符串字符串末尾的空格.
31

split(str="", num=string.count(str))

num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num 个子字符串

ss='*1*2*3*4*5*6*7*8'
aa=' a b c d e f'
print(aa.split())       #['a', 'b', 'c', 'd', 'e', 'f']
print(ss.split('*'))    #['', '1', '2', '3', '4', '5', '6', '7', '8']
print(ss.split('*',3))  #['', '1', '2', '3*4*5*6*7*8']
print(type(aa.split())) #<class 'list'>
32

splitlines([keepends])

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

print('ab c\n\nde fg\rkl\r\n'.splitlines(True))     #['ab c\n', '\n', 'de fg\r', 'kl\r\n']
print('ab c\n\nde fg\rkl\r\n'.splitlines())         #['ab c', '', 'de fg', 'kl']
33

startswith(str, beg=0,end=len(string))

类似于endswith
检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。
34

strip([chars])

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

swapcase()

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

a='asdfASDF'
print(a.swapcase()) #ASDFasdf
36

title()

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

translate(table, deletechars="")

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

intab='abcd'
outtab='1234'
c='sadfghh45321'
trantab=str.maketrans(intab,outtab)
print(c.translate(trantab))     #s14fghh45321
38

upper()

语法str.upper()
转换字符串中的小写字母为大写
39

zfill (width)

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

ss = "this is string example from runoob....wow!!!"
print (ss.zfill(40))    #this is string example from runoob....wow!!!
print (ss.zfill(50))    #000000this is string example from runoob....wow!!!
40

isdecimal()

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

ss = "runoob2016"
print (ss.isdecimal())  #False
ss = "23443434"
print (ss.isdecimal())  #True

s.isdigit、isdecimal 和 s.isnumeric 区别:

isdigit()

True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字

False: 汉字数字

Error: 无

isdecimal()

True: Unicode数字,,全角数字(双字节)

False: 罗马数字,汉字数字

Error: byte数字(单字节)

isnumeric()

True: Unicode数字,全角数字(双字节),罗马数字,汉字数字

False: 无

Error: byte数字(单字节)


num = "1"  #unicode
num.isdigit()   # True
num.isdecimal() # True
num.isnumeric() # True

num = "1" # 全角
num.isdigit()   # True
num.isdecimal() # True
num.isnumeric() # True

num = b"1" # byte
num.isdigit()   # True
num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'

num = "IV" # 罗马数字
num.isdigit()   # True
num.isdecimal() # False
num.isnumeric() # True

num = "四" # 汉字
num.isdigit()   # False
num.isdecimal() # False
num.isnumeric() # True

猜你喜欢

转载自blog.csdn.net/ab13653777822/article/details/81037531