字符串对象方法
文章目录
- 字符串对象方法
- str.replace(old, new[, count])
- str.strip([chars])
- str.ljust(width[, fillchar])
- str.partition(sep)
- str.startswith(prefix[, start[, end]])
- str.endswith(suffix[, start[, end]])
- str.isalnum() 、str.isalpha() 、str.isdigit() 、str.isspace()
- str.split(sep=None, maxsplit=-1)
- str.join(iterable)
- str.count(sub, [start[, end])
- str.find(sub[, start[, end]]) 、str.rfind(sub[, start[, end]]) 、str.index(sub[, start[, end]])、str.rindex(sub[, start[, end]])
- str.capitalize()、str.title()、 str.upper()、str.lower()、 str.swapcase()
str.replace(old, new[, count])
- old:旧字符串
- new:新字符串
- count:要替换的最大次数,默认为-1,替换所有能替换的
- 用新字符串替换旧字符串并返回
s = "Line1 Line2 Line4"
# 用 "b" 替换所有的 "Li"
rs = s.replace("Li", "b")
print(rs) # bne1 bne2 bne4
# 用 "b" 替换 "Li" 2次
rs = s.replace("Li", "b", 2)
print(rs) # bne1 bne2 Line4
str.strip([chars])
- chars:指定要移除的字符序列,如果没有指定,则默认移除空白符 (空格、换行符、制表符等)
- 从字符串左右两边删除指定的字符序列(会考虑chars的所有组合,注意这里是字符序列,会考虑该序列的所有组合,意思是只要包含该序列的字符都会删除)
- str.lstrip([chars]) 、str.rstrip([chars]) 也是同理,只不过一个是从左边来删除,一个从右边删除而已
str1 = ' \thello wrold h \n'
# 没有传参,删除字符串两边的空白符(空格、换行符、制表符)
print(str1.strip()) # ‘hello wrold h‘’
str2 = "ooho hello wrold"
# 移除str2头尾的字符"o",头部有两个连续的,都移除,尾部没有可以移除的
print(str2.strip('o')) # 'ho hello wrold'
# 会考虑"mecow."的所有组合情况来移除头尾的字符
str3 = 'www.example.com'
print(str3.strip("mecow.")) # 'xampl'
str.center(width[, fillchar])
- width:指定字符串长度
- fillchar:填充的字符,必须是单个字符,默认为空格符
- 返回长度为 width 的字符串,原字符串在其中靠左对齐,使用指定的 fillchar 填充空位;如果 width 小于等于 len(s) 则返回原字符串
- 当左右填充不平衡时,原字符串长度为奇数时,左边填充更少,原字 符串长度为偶数时,左边填充更多
str1 = "hello "
print(str1.center(11, "F"))
print(str1.center(3, "F"))
# 'FFFhello FF'
# 'hello '
str.ljust(width[, fillchar])
- width:指定字符串长度 fillchar:填充的字符,必须是单个字符,默认为空格符
- 返回长度为 width 的字符串,原字符串在其中靠左对齐,使用指定的 fillchar 填充空位;
- 如果 width 小于等于 len(s) 则返回原字符串
- str.rjust(width[, fillchar]) 也是同理,只不过原字符串在其中靠右对齐
str1 = "hello "
print(str1.ljust(11, "F"))
print(str1.ljust(3, "F"))
# 'hello FFFFF'
# 'hello '
print(str1.rjust(11, "F"))
print(str1.rjust(3, "F"))
# "FFFFFhello "
# 'hello '
str.partition(sep)
- sep:分隔符,可以是字符或者字符串
- 在 sep 首次出现的位置拆分字符串,返回一个包含三个元素的元组, 元素分别是分隔符之前的部分、分隔符本身,以及分隔符之后的部分。 如果分隔符未找到,则返回的元组包含原字符串本身以及两个空 字符串。
- str.rpartition(sep) 也是同理,只不过是从最后一次出现的位置拆分; 未找到分隔符返回的元组包含两个空字符串以及原字符串本身。其他 一样。
str1 = "hello world"
print(str1.partition("l"))
print(str1.partition("ll"))
print(str1.partition("hd"))
# ('he', 'l', 'lo world')
# ('he', 'll', 'o world')
# ('hello world', '', '')
print(str1.rpartition("l"))
print(str1.rpartition("ll"))
print(str1.rpartition("hd"))
# ('hello wor', 'l', 'd')
# ('he', 'll', 'o world')
# ('', '', 'hello world')
str.startswith(prefix[, start[, end]])
- prefix:匹配的前缀,可以是字符,字符串或者它们组成的元组(元组中只要一个元素满足即可)
- start:开始索引
- end:结束索引(不包括该索引)
- 如果字符串以指定的 prefix 开始,返回 True,否则返回 False;如果 有可选项 start,将从所指定位置开始检查; 如果有可选项 end,将在 所指定位置停止比较
str1 = "hello world"
print(str1.startswith("h"))
print(str1.startswith("he"))
print(str1.startswith(" w"))
print(str1.startswith(" w", 5, 8))
print(str1.startswith((" w", "h")))
# True
# True
# False
# True
# True
str.endswith(suffix[, start[, end]])
- suffix:匹配的后缀,可以是字符,字符串或者它们组成的元组(元组 中只要一个元素满足即可)
- start:开始索引
- end:结束索引(不包括该索引)
- 如果字符串以指定的 suffix 结束,返回 True,否则返回 False;如果 有可选项 start,将从所指定位置开始检查; 如果有可选项 end,将在 所指定位置停止比较
str1 = "hello world"
print(str1.endswith("d"))
print(str1.endswith("ld"))
# True
# True
print(str1.endswith("lo"))
print(str1.endswith("lo", 1, 5))
print(str1.endswith(("d", "lo")))
# False
# True
# True
str.isalnum() 、str.isalpha() 、str.isdigit() 、str.isspace()
- str.isalnum() 如果字符串中的所有字符都是字母、文字或数字,则返回 True,否则为 False
- str.isalpha() 如果字符串中的所有字符都是字母、文字,则返回 True,否则为 False
- str.isdigit() 如果字符串中的所有字符都是数字,则返回 True,否则为 False
- str.isspace() 如果字符串中只有空白符(空格、换行符、制表符等),则返回 True,否则为 False
str1 = "abc牛123"
print(str1.isalnum()) # True
print(str1.isalpha()) # False
str2 = "abc"
print(str2.isalpha()) # True
print(str1.isdigit()) # False
print(str2.isdigit()) # False
str3 = "123"
print(str3.isdigit()) # True
print(str1.isspace()) # False
str4 = " "
print(str4.isspace()) # True
str5 = "\t"
print(str5.isspace()) # True
str6 = "\n"
print(str6.isspace()) # True
str.split(sep=None, maxsplit=-1)
- sep:用于分割字符串的分隔符, 默认为所有的空白符(空格、换行、 制表符等), 并丢弃结果中的空字符串
- maxsplit:最大分隔次数,默认为-1,即分隔所有
- 通过指定分隔符对字符串进行分割, 以字符串列表的形式返回(分割结 果不包括分隔符)
- str.rsplit(sep=None, maxsplit=-1) 也是同理,只不过是rsplit从右边开始
s = " Line1-abcdef \nLine2-abc \nLine4-abcd"
# 默认按照所有的空白符(空格、换行、制表符等)来分割, 并从结果中丢弃空字符串
a = s.split()
print(a)
# ['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
# split()默认参数是去除字符串两边的空白符,然后以字符串中间的空白符来分割字符串的,也就是不会产生空字 符。
a = s.split(" ")
print(a)
# ['', 'Line1-abcdef', '\nLine2-abc', '\nLine4-abcd']
# 按照指定的"Li"来分割2次
a = s.split("Li", 2)
print(a)
# maxsplit按照指定的"Li"从右边开始
a = s.rsplit("Li", 2)
print(a)
# [' ', 'ne1-abcdef \n', 'ne2-abc \nLine4-abcd']
# [' Line1-abcdef \n', 'ne2-abc \n', 'ne4-abcd']
str.join(iterable)
- iterable:包括 string、list、tuple、dict、set等等
- 将可迭代对象中的元素**(元素必须是字符串类型)**以指定的字符连接,返回新的字符串
a = "\\" # 单个反斜杠
s1 = "hello world"
print(a.join(s1)) # h\e\l\l\o\ \w\o\r\l\d
s2 = ["1", "2", "3", "4"]
print(a.join(s2)) # 1\2\3\4
s3 = ("1", "2", "3", "4")
print(a.join(s3)) # 1\2\3\4
# 字典只取键, 不取值
s4 = {"身高": 175, "体重": 65}
print(a.join(s4)) # 身高\体重
# 集合无序,所以这里结果不是确定的
s5 = {"1", "2", "3", "1"} # 去重
print(a.join(s5)) # 1\2\3
str.count(sub, [start[, end])
- sub:指定的子字符串
- start:字符串开始搜索的位置索引,默认为0
- end:字符串中结束搜索的位置索引(不包括这个),默认为 len(str)
- 返回子字符串在字符串中出现的非重叠的次数(默认全局搜索)
a = "hello world"
a1 = a.count("l") # 3
a2 = a.count("l", 0, 3) # 1
a3 = a.count("hel", 0, 3) # 1
a4 = a.count("hle", 0, 3) # 0
print(a1) # 3
print(a2) # 1
print(a3) # 1
print(a4) # 0
str.find(sub[, start[, end]]) 、str.rfind(sub[, start[, end]]) 、str.index(sub[, start[, end]])、str.rindex(sub[, start[, end]])
- str.find(sub[, start[, end]]) 返回从左开始第一次找到指定子字符串时的索引, 找不到就返回 -1
- str.rfind(sub[, start[, end]]) 返回从右开始第一次找到指定子字符串时的索引, 找不到就返回 -1
- str.index(sub[, start[, end]]) 类似于find(),唯一不同在于,找不到就会报错,其他都一样
- str.rindex(sub[, start[, end]]) 类似于rfind(),唯一不同在于,找不到就会报 错,其他都一样
- sub:指定的子字符串
- start:字符串开始搜索的位置索引,默认为0
- end:字符串中结束搜索的位置索引(不包括这个),默认为 len(str) 注意:返回索引时,是返回原字符串中的索引值
s = "hello world"
a = s.find("l") # 2
b = s.rfind("l") # 9
print(a, b)
a = s.find("l", 4) # 9
b = s.rfind("l", 4) # 9
print(a, b)
a = s.find("ell", 1, 5) # 1
b = s.rfind("ell", 1, 5) # 1
print(a, b)
str.capitalize()、str.title()、 str.upper()、str.lower()、 str.swapcase()
- str.capitalize() 将字符串的首字母变成大写,其他字母变小写,并返回
- str.title() 将字符串中所有单词的首字母变成大写,其他字母变小写,并返回
- str.upper() 将字符串中所有字符变成大写,并返回
- str.lower() 将字符串中所有字符变成小写,并返回
- str.swapcase() 将字符串中所有大写字符变成小写,小写变成大写,并返回
a = "hello world"
b = a.capitalize()
print(b) # Hello world
c = a.title()
print(c) # Hello World
d = a.upper()
print(d) # HELLO WORLD
e = d.lower()
print(e) # hello world
f = c.swapcase()
print(f) # hELLO wORLD