字符串的拼接
a = "hello"
b = "klvchen"
c = a + b
print(c)
结果:
helloklvchen
注意:该方法效率比较低,推荐使用 join 方法
a = "hello"
b = "klvchen"
c = " ".join([a, b])
print(c)
结果:
hello klvchen
字符串的各种方法
统计元素个数
str = "hello klvchen"
print(str.count(‘l‘))
结果:
3
首字母大写
str = "hello klvchen"
print(str.capitalize())
结果:
Hello klvchen
居中
str = "hello klvchen"
print(str.center(50,‘#‘))
结果:
##################hello klvchen###################
判断是否以某个内容结尾
str = "hello klvchen"
print(str.endswith(‘chen‘))
结果:
True
判断是否以某个内容开始
str = "hello klvchen"
print(str.startswith(‘tt‘))
结果:
False
设置 tab 的 size
str = "hello \tklvchen"
print(str.expandtabs(tabsize=30))
结果:
hello klvchen
查找第一个元素,并返回索引
str = "hello klvchen"
print(str.find(‘t‘))
print(str.find(‘l‘))
结果:
-1
2
format
str = "hello {name}"
print(str.format(name=‘klvchen‘))
结果:
hello klvchen
format_map
str = "hello {name} is {age}"
print(str.format_map({‘name‘:‘klvchen‘,‘age‘:28}))
结果:
hello klvchen is 28
去除字符串两边空格及tab
str = ‘ hello world ‘
print(str.strip())
结果:
hello world
替换字符串
str = ‘hello world‘
print(str.replace(‘o‘, ‘a‘)) # 全部替换
print(str.replace(‘o‘, ‘a‘, 1)) # 只替换一次
结果:
hella warld
hella world
切割字符串
str = ‘hello world‘
print(str.split(‘ ‘))
结果:
[‘hello‘, ‘world‘]