Python字符串操作方法总结

检测是否包含在其中,如果是返回开始的索引值,否则返回-1

b2 = a.find(“b”)


b3 = a.index(a)
print(b3)

跟find()方法一样,只不过如果str不在 mystr中会报一个异常.

b3_1 = a.index(3a)
print(b3_1)

返回 str在start和end之间 在 mystr里面出现的次数

b4 = a.count(“f”)
print(b4)
b4_1 = a.count(“f”, 2, 9)
print(b4_1)

把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.

b5 = a.replace(“f”, “F”)
print(b5)

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

b6 = a.split(“f”)
print(b6)
b6_1 = a.split(“f”, 1)
print(b6_1)


a = “abcdef”

把字符串的第一个字母大写

b = a.capitalize()
print(b)

a = “hello world”
#把每个单词的首字母大写
b = a.title()
print(b)

a = “hello world”
#检查字符串是否是以 hello 开头, 是则返回 True,否则返回 False
b = a.startswith(“llo”)
print(b)

a = “hello world.jpg”
#检查字符串是否以.jpg结束,如果是返回True,否则返回 False
b = a.endswith(".jpg")
print(b)

a = “HELLO world”
#转换 mystr 中所有大写字符为小写
b = a.lower()
print(b)

a = “hello WORLD”
#转换 mystr 中的小写字母为大写
b = a.upper()
print(b)

#是否全为大写字母,是的话返回True,否则返回False
a = “HELLO WORLD”
b = a.isupper()
print(b)
#是否全为小写字母,是的话返回True,否则返回False
a = “hello world”
b = a.islower()
print(b)

a = “hello world”
#返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串
b = a.ljust(15)
print(b)

a = “hello world”
#返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串
b = a.rjust(15)
print(b)

a = “hello world”
#返回一个原字符串居中,并使用空格填充至长度 width 的新字符串
b = a.center(15)
print(b)

a = " hello world"
#删除 mystr 左边的空白字符
b = a.lstrip()
print(b)

a = "hello world "
#删除 mystr 字符串末尾的空白字符
b = a.rstrip()
print(b)

a = " hello world "
#删除mystr字符串两端的空白字符
b = a.strip()
print(b)

a = “abefcdef”
#类似于 find()函数,不过是从右边开始查找.
ret1 = a.rfind(“f”)
print(ret1)

#类似于 index(),不过是从右边开始.
ret2 = a.rindex(“e”)
print(ret2)

#把mystr以str分割成三部分,str前,str和str后
ret3 = a.partition(“e”)
print(ret3)

#类似于 partition()函数,不过是从右边开始.
ret4 = a.rpartition(“e”)
print(ret4)

a = “a\nb\nc\n”
#按照行分隔,返回一个包含各行作为元素的列表
ret5 = a.splitlines()
print(ret5)

a = “abefcdef”
#类似于 find()函数,不过是从右边开始查找.
ret1 = a.rfind(“f”)
print(ret1)

#类似于 index(),不过是从右边开始.
ret2 = a.rindex(“e”)
print(ret2)

#把mystr以str分割成三部分,str前,str和str后
ret3 = a.partition(“e”)
print(ret3)

#类似于 partition()函数,不过是从右边开始.
ret4 = a.rpartition(“e”)
print(ret4)

你可能感兴趣的:(Python基础)