字符串的常用方法

1、转大写/小写

1 str1='helloworld'
2 # str.upper()#字符串转大写
3 str2=str1.upper()
4 print(str2)
5 
6 str2='HEELO'
7 # str.lower()#转小写
8 print(str2.lower())

2、判断是否全是大写/小写

1 str.isupper()#判断是否全大写
2 str.islower()#判断是否全小写

3、判断字符串是否全部由空白字符组成

1 str.isspace() #返回True or False
2 
3 str4='\n'  #换行符也是空白符

4、判断字符串是否以指定的子串开头/结尾

1 str.startswith()#判断字符串是否以指定子串开头
2 str.endswith()#判断字符串是否以指定子串结尾

5、返回指定子串的索引位

1 str.index()#返回指定的子串再字符串中的索引位,子串不存在会报错
2 str.find()#返回指定的子串再字符串中的索引位,不存在返回-1

6、返回指定子串在字符串中出现的次数

1 str.count()

7、把字符串的首字母转为大写

str.capitalize()

8、切割字符串,返回的是列表

str.split()#按空格切割
print(str.split(',')) #指定按什么切割,字符串中要有指定的东西
a='as,df,g'.split(',')
print(a)

9、用分隔符将字符串拼接起来

1 str.join()#以当前的字符串为分隔符,将可迭代对象中字符串拼接起来
2 print('_'.join('hello'))   #h_e_l_l_o
3 
4 #整型、布尔值、浮点数都不可迭代,列表必须是纯字符的才可以
5 
6 #总而言之,拼接的元素必须是字符

10、替换

1 #str.replace()#使用指定的子串替换成新的子串,可选择替换次数
2 str7='hello xx xx xx'
3 print(str7.replace('xx','cc',1))

11、将字符串转为字节

#str.encode()
str11='as d34 '.encode()
print(type(str11))

12、判断字符串是否全由xxx组成

 1 #str.isalpha()#判断字符串是否全部由英文字母(或中文)组成
 2 '阿斯弗'.isalpha()  本身返回的就是True
 3 
 4 # str.isdigit()#判断是否全由数字组成
 5 print('12a'.isdigit())
 6 
 7 # str.isalnum()#判断是否由英文字母或数字(或中文)组成
 8 print('a3n语文'.isalnum())
 9 
10 # str.isascii()#判断字符串是否全由ascci码中的字符组成
11 print('a2D'.isascii())

13、去掉空格符、换行符、制表符

1 #str.strip()#默认去掉字符串两边的空格、换行符、制表符
2 # str.lstrip()#去左边的
3 # str.rsplit()#去掉右边的

 

posted @ 2022-06-23 21:08  爱coding的果妈  阅读(139)  评论(0)    收藏  举报