- center方法
用于将一个字符串在一定宽度的区域居中显示,并在字符串的两侧填充指定的字符(只能是长度为1的字符串),默认填充空格。
# 使用cnter方法让“hello”在宽度为30的区域居中显示,两侧区域填充空格
print("<" + "hello".center(30) + ">")
# 使用format方法让"hello”在宽度为30的区域居中显示,两侧区域填充空格
print("<" + "{:^30}".format("hello") + ">")
# 使用cnter方法让“hello”在宽度为30的区域居中显示,两侧区域填充星号(*)
print("<" + "hello".center(30, '*') + ">")
# 使用format方法让“hello”在宽度为30的区域居中显示,两侧区域填充星号(*)
print("<" + "{:*^30}".format("hello") + ">")
输出结果:
< hello >
< hello >
<************hello*************>
<************hello*************>
- find方法
find方法用于在一个大字符串中查找子字符串,如果找到,find方法返回子字符串的第1个字符在大字符串中出现的位置,如果未找到,find方法返回-1。
s = "hello world"
# 在s中查找“world”,运行结果为:6
print(s.find("world"))
# 在s中查找“ok”,未找到,运行结果为:-1
print(s.find("ok"))
find方法还可以通过第2个参数指定开始查找的位置
s = "hello world"
# 从开始的位置查找“o”,运行结果为:4
print(s.find("o"))
# 从位置5开始查找“o”,运行结果为:7
print(s.find("o",5))
find方法还可以通过第3个参数指定结束查找的位置
s = "hello world"
# 从第5个位置开始查找,到第8个位置查找结束,运行结果为:-1
print(s.find("l", 5, 9))
# 从第5个位置开始查找,到第9个位置查找结束,运行结果为:9
print(s.find("l", 5, 10))
- join和split方法
用于连接序列中的元素,是split方法的逆方法,**连接的序列元素必须时字符串类型,如果是其他类型,会抛出异常。
split通过分隔符将一个字符串拆成一个序列,默认为空格。
list = ['1','2','3','4']
print('/'.join(list))
str = '/1/2/3/4'
print(str.split('/'))
输出结果:
1/2/3/4
['', '1', '2', '3', '4']
- lower、upper方法和capwords函数
lower方法和upper方法分别用于将字符串中的所有字母字符转换为小写和大写。
capwords函数会将一个字符串中独立的单词的首字母都转行为大写。
# 将"HELLO"转换为小写,运行结果为:hello
print("HELLO".lower())
# 将"hello"转换为大写,运行结果为:HELLO
print("hello".upper())
# 将单词首字母转为大写,I Not Only Like Python, But Also Like Kotlin.
import string
print(string.capwords("I not only like python, but also like Kotlin."))
- replace方法和translate方法、maketrans方法
用于将一个字符串中的子字符串替换为另一个字符串。该方法返回被替换后的字符串,如果在原字符串中未找到要替换的子字符串,那么replace方法就返回原字符串。
# 运行结果:This is a bike
print("This is a car".replace("car", "bike")
translate与replace方法类似,都是用来替换字符串中的某一部分,只是translate方法只用来替换单个字符,而replace方法可以用来替换一个子字符串。
# 创建一张替换表,在这里指定了maketrans方法的3个参数,用于指定要删除的字符
s = "I not only like python, but also like Kotlin."
table = s.maketrans("ak", "$%", " ")
# 根据替换表替换s中相应的字符,并删除所有的空格
# 输出结果:Inotonlyli%epython,but$lsoli%eKotlin.
print(s.translate(table))
注意
1、translate方法替换的不止一个字符,如果在原字符串中有多个字符满足条件,那么就替换所有满足条件的字符。
2、maketrans方法的第三个参数指定了要从原字符串中删除的字符,不是字符串。如果第三个参数指定的字符串长度大于1,那么在删除字符时只会考虑其中的每个字符。
- strip方法
用于截取字符串的前后空格,以及截取字符串前后指定的字符。
# 截取字符串前后空格,运行结果:< geekori.com >
print(" < geekori.com > ".strip())
# 指定要截取字符串前后的字符是空格、*和&,运行结果:Hello& *World
print("*** &* Hello& *World**&&&".strip(" *&"))