增
1、使用{}的方法
s1 = 'Hello {}! My name is {}.'.format('World', 'Python猫')
print(s1)
s2 = 'Hello {0} My name is {1}.'.format('world','Python 猫')
print(s2)
s3 = 'Hello {name1}! My name is {name2}.'.format(name1='world',name2='Python 猫')
print(s3)
2、%的方法
print('%s %s' % ('Hello', 'world'))
3、使用()类似元组的方法
s_tuple = ('Hello',' ','world')
s_like_tuple = ('Hello' ' ' 'world')
print(s_tuple)
print(s_like_tuple)
type(s_like_tuple)
4、面向对象模板拼接
from string import Template
s = Template('${s1} ${s2}!')
print(s.safe_substitute(s1='Hello',s2='world'))
5、+号方式
str_1 = 'Hello world! '
str_2 = 'My name is Python猫.'
print(str_1 + str_2)
print(str_1)
6、join()拼接方式
str_list = ['Hello','wordl']
str_join1 = ''.join(str_list)
str_join2 = '-'.join(str_list)
print(str_join1)
print(str_join2)
7、f-string
name = 'world'
myname = 'python_cat'
words = f' Hello {name}. My name is {myname} .'
删
-
去除字符串空格 / 或回车、换行符
去除字符串开头或结尾空格 .strip(), lstrip(), rstrip()
去除全部空格:
法一:
字符串替换 replace(old, new, count)
法二:
join为字符字符串合成传入一个字符串列表,
split为字符串分割可以按规则进行分割,分割后为列表
改
- 字母大小写转换
所有字符转大写 .upper()
所有字符转小写 .lower()
第一个字母转大写 .capitalize()
每个单词的首字母转大写 .title()
查
- 字符串判断
判断字符串是否只包含字母或数字 .isalnum()
判断字符串是否只包含字母 .isalpha()
判断字符串是否只包含数字 .isdigit()
判断字符串是否全部为大写 .isupper()
判断字符串是否全部为小写 .islower()
判断字符串是否都是首字母大写 .title()
判断字符串是否全部为空白字符、\t、\r、\n .isspace()
判断字符串是否包含字串 使用成员操作符 in
- 字符串查找
查找指定范围内字符串A中是否包含str find(str, beg=0, end=len(string))
#返回值为str的下标,若str不存在,则报错(ValueError)