Python 字符串常用操作

python常用字符串操作命令


 

Str命令操作如图:

这里用tt = "I dead love python,Python love me too"举例:

1.Str.find()

 

1 tt.find("love")
2 #返回第一个对应字符的下标,未找到返回-1

 

2.Str.rfind()

tt.rfind("love")
#从后向前查找对应字符,并返回第一个对应字符脚标;未找到返回-1

3.Str.index()

tt.index("love")
tt.index("dd")
index() 与 find() 功能类似,但返回略有不同;区别在于index未查询到是返回异常:ValueError: substring not found

4.Str.rindex()

tt.rindex("love")
tt.rindex("dd")
功能与find()相同,返回略有不同,具体参考index()

5.Str.count()

tt.count("love")
tt.count("dd")
返回对应字符在字符串中出现的次数,未出现返回:0

6.Str.replace()

#把字符串中“"love" 替换成 "like",count为指定替换数量,若count指定,则替换数不超过count;
#注意:这里只能返回参数,源字符串不改变。
tt.replace("love", "like")
tt.replace("love", "like", 1)

7.Str.split()   (如需按照换行符分割,请点击参考:Splitlines函数)

#把字符串进行切割;示例中使用的是空格
tt.split(" ")

8.Str.capitalize()

#字符串首字母大写,仅第一个字母大写
ttt = "iLIKEYOU"
ttt.capitalize()

9.Str.tittle()

#字符串中所有单词首字母大写
tt.title()

10.Str.startswith()

tt.startswith("I dead")
tt.startswith("I dead  ")
#是返回True, 否返回 False.

11.Str.esdswith()

tt.endswith("too")
tt.endswith("toooo")
#与startswith一致;

12.Str.lower()/Str.upper()

tt.lower()  #全部转换成小写字母
tt.upper()  #全部转换成大写字母

 

13.Str.center() / Str.ljust() / Str.rjust()

1 tt.center(100) #字符串在100px内居中显示
2 tt.ljust(100) #字符串在100px内左对齐显示
3 tt.ljust(100) #字符串在100px内右对齐显示

14.Str.strip() / Str.lstrip() / Str.rstrip()

spacett = tt.center(60)
print(spacett)          
spacett.strip() #删除字符串左右两边的空格
spacett.lstrip() #删除字符串左边的空格
spacett.rstrip() #删除字符串右边的空格

15.Str.partition()

tt.partition() 
#
'''partition() 方法用来根据指定的分隔符将字符串进行分割。如果字符串包含指定的分隔符,则返回一个3元的元组,
第一个为分隔符左边的子串, 第二个为分隔符本身,第三个为分隔符右边的子串。'''

16.Str.splitines()  按照换行分分割

该功能将" " 删除,并分割成列表

17.Str.isdigit() Str.isalpha() Str.isalnum() Str.isspace()

isdigit() 判断是否是纯数字

isalpha() 判断是否是纯字母

isalnum() 判断是否是数字或字母

isspace() 判断是否是空格空

18.Str.join()

用字符串b连接列表a中的元素

深度学习 开拓视野
原文地址:https://www.cnblogs.com/janeyu/p/10795175.html