python 常用的字符串方法

1、center()

字符串居中输出

str1 = "OYS will be the best"
str1.center(50)
# '               OYS will be the best               '

2、find()

在字符串中指定范围查找字串,并返回第一个字符索引,否则返回-1

str1 = "OYS will be the best"
print(str1.find(" w"))
# 3

3、join()

作用与split相反,用于合并序列的元素
让我们可以将使用列表方法处理过的字符串元素重新转换成字符串形式

seq = [1,2,3,4,5,6]
sep = '+'
sep.join(seq)

需要str对象

TypeError: sequence item 0: expected str instance, int found
seq = [1,2,3,4,5,6]
for i in range(len(seq)):
    seq[i] = str(seq[i])
sep = '+'
sep.join(seq)
# '1+2+3+4+5+6'

4、count()

统计字符串中子字符串的出现次数
可选参数寻找索引范围 str.count(sub, start= 0,end=len(string))

str1 = "OYS will be the best"
str1.count("b")
# 2

5、endswith()

str.endswith(suffix[, start[, end]])
检查指定范围字符串是否以子字符串结尾

str1 = "OYS will be the best"
str1.endswith("best")
# True

6、split()

其作用与join相反,用于将字符串拆分为序列,拆分的元素放置于列表中

x = '1+2+3+4+5+6'
x.split("+")
# ['1', '2', '3', '4', '5', '6']

如果没有指定分隔符,将默认在单个或者多个连续的空白字符处(空格、制表符、换行符)进行拆分

7、strip()

将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果

names = ["gumby", "smith", "jones"]
name = " gumby "
if name.strip() in names:print("Found it!")
# Found it!

还可以在一个字符串参数中指定要删除哪些字符,但是只删除字符串开头跟末尾的字符

str1 = "OYS will be best the best"
str1.strip("best")
# 'OYS will be best the '

8、lower()

返回字符串的小写版本

str1 = "OYS will be best the best"
str1.lower()
# 'oys will be best the best'

猜你喜欢

转载自blog.csdn.net/Winds_Up/article/details/108932161