python字符串方法

python字符串内建函数
1、capitalize()

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

str = "hello world"
print ("str.capitalize() : ", str.capitalize())
# str.capitalize() :  Hello world
2 、title()

所有单词的首个字母转化为大写

str = "this is string example....wow!!!"
print (str.title())
#This Is String Example....Wow!!!
3、istitle()

检测字符串中所有的首字母是否都为大写

str = "Hello World"
print (str.istitle()) # true
4、lower()

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

str.lower()
5、upper()

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

str.upper()
6、swapcase()

用于对字符串的大小写字母进行转换

str.swapcase()
7、center()

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

str.center(width[, fillchar])

print ("str.center(40, '*') : ", str.center(40, '*'))
# str.center(40, '*') :  **************hello world***************
8、ljust()

ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

  • width -- 指定字符串长度。
  • fillchar -- 填充字符,默认为空格。
str.ljust(width[, fillchar])
str = "hello world!!!"
print (str.ljust(30, '*'))  
#hello world!!!****************
9、rjust()

返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串。

str = "hello world!!!"
print (str.rjust(30, '*'))  
#****************hello world!!!
10、zfill()

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

str = "this is string example....wow!!!"
print ("str.zfill : ",str.zfill(40))
# str.zfill :  00000000this is string example....wow!!!
11、lstrip()

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

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
12、rstrip()

删除 string 字符串末尾的指定字符(默认为空格)。

str = "     this is string example....wow!!!     "
print (str.rstrip())
str = "*****this is string example....wow!!!*****"
print (str.rstrip('*'))

输出结果

this is string example....wow!!!
*****this is string example....wow!!!
13、strip()

用于移除字符串头尾指定的字符(默认为空格)或字符序列

str = "*****this is **string** example....wow!!!*****"
print (str.strip( '*' ))  # 指定字符串 *
# this is **string** example....wow!!!
14、count()

用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

str.count(sub, start= 0,end=len(string))
sub -- 搜索的子字符串
start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。

str.center(width[, fillchar])

sub='o'
print ("str.count('o') : ", str.count(sub))
print ("str.count('run', 0, 5) : ", str.count(sub,0,5))
# str.count('o') :  2
# str.count('run', 0, 5) :  1
15、index()

字符串中是否包含子字符串 str

  • beg -- 开始索引,默认为0。
  • end -- 结束索引,默认为字符串的长度
  • 如果str不在 string中会报一个异常
  • 如果包含子字符串返回开始的索引值,否则抛出异常。
str.index(str, beg=0, end=len(string))
str1 = "hello world"
str2 = "world";
print (str1.index(str2))
print (str1.index(str2, 5))
print (str1.index(str2, 10))

输出结果:

6
6
Traceback (most recent call last):
File "D:/pythonProject/demo/venv/study/Number.py", line 31, in
print (str1.index(str2, 10))
ValueError: substring not found

16、rfind()

rfind() 返回字符串最后一次出现的位置,如果没有匹配项则返回-1

17、rindex()

子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。

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

print (str1.rindex(str2))
print (str1.rindex(str2,10))

输出结果

5
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print (str1.rindex(str2,10))
ValueError: substring not found
18、max()

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

max(str)

19、min()

返回字符串中最小的字母

min(str)
20、endswith()

endswith() 方法用于判断字符串是否以指定字符串结尾,如果以指定后缀结尾返回 True,否则返回 False。

可选参数 "start" 与 "end" 为检索字符串的开始与结束位置。

str.endswith(suffix[, start[, end]])
Str='hello world!!!'
suffix='!!'
print (Str.endswith(suffix))
print (Str.endswith(suffix,10))
suffix='hello'
print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))

输出结果:

True
True
False
False

21 、startswith()

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

str = "this is string example....wow!!!"
print (str.startswith( 'this' ))   # 字符串是否以 this 开头
print (str.startswith( 'string', 8 ))  # 从第九个字符开始的字符串是否以 string 开头
print (str.startswith( 'this', 2, 4 )) # 从第2个字符开始到第四个字符结束的字符串是否以 this 开头

输出结果:

True
True
False
22、isdigit()

检测字符串是否只由数字组成

str = "123456"; 
print (str.isdigit()) # true
23、isnumeric()

检测字符串是否只由数字组成,数字可以是: Unicode 数字,全角数字(双字节),罗马数字,汉字数字。

str = "23443434"
print (str.isnumeric())  # true
24、isdecimal()

检查字符串是否只包含十进制字符

str = "runoob2016"
print (str.isdecimal()) # false
str = "23443434"
print (str.isdecimal()) #true
isdigit()
True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
False: 汉字数字
Error: 无
    
isnumeric()
True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
False: 无
Error: byte数字(单字节)
isdecimal()

True: Unicode数字,,全角数字(双字节)
False: 罗马数字,汉字数字
Error: byte数字(单字节)
25、isspace()

检测字符串是否只由空白字符组成

str = "       " 
print (str.isspace()) # true
26、isupper()

检测字符串中所有的字母是否都为大写

str = "HELLO"
print (str.isupper()) # true
27、islower()

检测字符串是否由小写字母组成

str = "hello world"
print (str.islower()) # true
28、isalnum()

isalnum() 方法检测字符串是否由字母和数字组成

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

str.isalnum()
str = "hi2021"  # 字符串不能有空格
print(str.isalnum())  # 输出true
29、isalpha()

Python isalpha() 方法检测字符串是否只由字母或文字组成。

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

str.isalpha()
str = "hi新年好"
print(str.isalpha())  # true
30、0replace()

replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

str.replace(old, new[, max])
str = "this is string isisexample....wow!!!"
print(str.replace("is", "was", 3))
# thwas was string wasisexample....wow!!!
31、len()

返回字符串的长度

>>> str = "hello"
>>> len(str)     #5
32、join()

用于将序列中的元素以指定的字符连接生成一个新的字符串

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

输出结果

h-e-l-l-o
hello

33、split()

通过指定分隔符对字符串进行切片,如果第二个参数 num 有指定值,则分割为 num+1 个子字符串

str.split(str="", num=string.count(str))
str = "this is string example....wow!!!"
print (str.split( ))       # 以空格为分隔符
print (str.split('i',1))   # 以 i 为分隔符
print (str.split('w'))     # 以 w 为分隔符

输出结果

['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']
34、splitlines()

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

str.splitlines([keepends])
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
>>>
35、encode()

编码方式,errors参数可以指定不同的错误处理方案。

str.encode(encoding='UTF-8',errors='strict')
str = "hello world"
print ("str.capitalize() : ", str.capitalize())
# str.capitalize() :  Hello world
36、decode()

解码方式

str = "编码格式";
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'))

输出结果

编码格式
UTF-8 编码: b'\xe7\xbc\x96\xe7\xa0\x81\xe6\xa0\xbc\xe5\xbc\x8f'
GBK 编码: b'\xb1\xe0\xc2\xeb\xb8\xf1\xca\xbd'
UTF-8 解码: 编码格式
GBK 解码: 编码格式

37、expandtabs()

把字符串中的 tab 符号 \t 转为空格,tabsize -- 指定转换字符串中的 tab 符号 \t 转为空格的字符数。

tab 符号 \t 默认的空格数是 8,在第 0、8、16...等处给出制表符位置,如果当前位置到开始位置或上一个制表符位置的字符数不足 8 的倍数则以空格代替。

str.expandtabs(tabsize=8)
str = "hello\t12345\tworld"
print( str)
print( str.expandtabs())
print( str.expandtabs(2))

输出结果:

hello 12345 world hello有5个字符,所以后面的\t填充了3个空格 ,12345有5个字符,所以后面的\t填充了3个空格
hello 12345 world
hello 12345 world

38、translate()

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

str = "hello world"
print ("str.capitalize() : ", str.capitalize())
# str.capitalize() :  Hello world
39、maketrans()
  • intab -- 字符串中要替代的字符组成的字符串。
  • outtab -- 相应的映射字符的字符串。
str.maketrans(intab, outtab)
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
print(trantab)
str = "this is string example....wow!!!"
print (str.translate(trantab))

输出结果:

{97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
th3s 3s str3ng 2x1mpl2....w4w!!!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值