8.字符串的格式化输出
方式1:等价于%s,先把文本编辑好 想要占位的地方用{} 可以多处占位 通过变量名.format 格式化输出
res1 = 'my name is {},my age is {}'print(res1.format('joker',18))
方式2:支持索引取值 并且可以重复使用
res2 = 'my name is {0},my age is {0}{1}{0}{0}'print(res2.format('joker',18))
方式3:通过关键字取值 (按K取值) 并且可以重复使用
res3 = '{name} {name} my name is {name} {name},my age is {age} {age}'print(res3.format(name = 'joker', age = 18))
方式4:使用变量名 然后绑定数据值 在使用时将变量名输入{}内即可 并且也可以重复使用 最推荐使用的一种方式
name = 'joker'
age = 18print(f'my name is {name},my age is {age}')
10.判断字符串开头或结尾
关键字(.startswith)# 判断字符串开头,(.endswith) # 判断字符串结尾str = 'jason say ha ha ha heiheihei'print(str.startswith('jason')) # Trueprint(str.startswith('a')) # Falseprint(str.startswith('ja')) # Trueprint(str.endswith('heiheihei')) # Trueprint(str.startswith('hei')) # Falseprint(str.startswith('i')) # False
可以查找单个字符 也可以查找多个字符 返回来的结果是布尔值
11.字符串的替换
关键字(.replace)
res = 'lisa lisa lisa SB SB SB'print(res.replace('lisa', 'tony')) # tony tony tony SB SB SB 从左往右全部替换print(res.replace('lisa', 'tony',2)) # tony tony lisa SB SB SB 从左往右指定替换
12.字符串的拼接
12.1 字符串支持 + 号拼接
a = 'hello'
b = 'world'print(a+b) # helloworld
12.2 字符串支持 * 号重复
a = 'hello'
b = 'world'print(a * 10)
12.3 jojo拼接
print(''.jojo ['hello','world','hh']) # helloworldhhprint('|'.jojo ['hello','world','hh']) # hello|world|hhprint('$'.jojo ['hello','world','66']) # 拼接列表中的数据类型必须是字符串 否则会报错
14.查找每个字符的索引值
关键字:(.index)
res = 'hello,world,lll'print(res.index('d')) # 10print(res.index('d',0,5))
使用.index 查找索引 如果没有则会报错
关键字:(.find)
res = 'hello,world,lll'print(res.find('d')) # 10print(res.find('d',0,5))
使用.find 查找索引 如果没有则返回-1
15.正文相关操作
关键字:(.title) 首字母大写
res = 'my name is joker'print(res.title()) # My Name Is Joker
关键字:(.capitalize) 只有第一个字母大写
res = 'my name is joker'print(res.capitalize()) # My name is joker