字符串常见操作

1、find  查找

my_str = "dfsadfjhudfdfsfirndf"

my_str.find("fj") #如果返回-1表示没有找到, 如果有返回,返回的值表示第一个字母f的下标,如果有两个相同,则返回最近一个,my_str.rfind("")从右边开始找

2、count  统计

my_str("df") # 统计df的个数

3、 replace 替换

my_str.replace(str1,str2,  my_str.count(str1))    # 把 my_str中的str1替换为str2, 如果count指定,则替换不超过count 次

注意:字符串是不可变类型,在调用replace时返回一个新的字符串,不是把原来的改了,需要爪个变量重新接收他

my_str.replace("df","DF",  5)   #替换5次,不写默认全替换

4、split  切割,返回值是一个列表

以str为分隔符切片my_str,如果 maxsplit有指定值,则仅分隔maxsplit个字符串

my_str.split("  ") # 如果按照 空格切割,切完之后就没有空格了。 这成为损耗

 

 

5、title  把字符串的每个词首字母大写    capitalize 首字母大写

6、startswith 检查字符串是否以某个字符串开头,是则返回True,否则返回False    endswith  检查字符串是否以某个字符串结尾

eg :  my_str.startswith("hello")  my_str.endswith("hello")

endswith 可以判断文件名是否是指定文件名结尾的、

7、lower  转换字符串中所有的字符为小写,不管之前的字符串是大写还是小写    upper() 转换字符串中的字母 为大写、

eg:   email = "ggcYhn"   email.lower() ==>ggcyhn   email.upper() ==>  GGCYHN

8、ljust  左对齐   rjust  右对齐  enter 居中

eg: lyric = "想和你一起看大海"

lyric.center(50)  #居中   50屏幕的长度

lyric.ljust(50)   #左对齐

lyric.rjust50)   # 右对齐

9、lstrip  删除左边的空白字符   rstrip 删除右边的空白字符   strip删除字符串两边的空白字符

eg:  lyric.lstrip()  lyric.rstrip()  lyric.strip()

10、partition  把以另一个字符串作为分割,分割为前,中, 后 。  rpartition 从右边开始分割

eg:my_str = "hello world and you"

my_str.patition("and")  ===>('hello world ', 'and', 'you')

11、splitlines  按照行分割,返回一个包含各行作为元素的列表

eg: file_name =  "121\n33\nhhh"    file_name.splitlines  ===>['121', '33','hhh']

12、isalpha  如果字符串都是字母,则返回True,否则返回False,判断里面是不是纯字母

13、isdigit   判断是不是纯数字的字符串

14、isalnum()    如果字符都是字母或者数字则返回True,否则返回False 

15、isspace  判断字符串中是都只包含空格,是则返回True

16、join 

eg:

names = ["aaa", "abc", "ddd"]

a = "_"

a.join(names) ==> 'aaa_abc_ddd"

posted on 2020-03-25 23:29  pooopun  阅读(132)  评论(0编辑  收藏  举报

导航