1.%方式
%格式化字符串的方式继承自古老的C语言
示例:
print('%s %s' % ('hello', 'world')) hello world
类似的占位符还有%d(代表整数),%f(代表浮点数),%x(代表十六进制数)
2.format
s1 = 'hello {}! my name is {}'.format('world', 'python') print(s1) hello world! my name is python
3.类似元组方式
s_tuple = ('hello', ' ', 'world') s_like_tuple = ('hello' ' ' 'world') print(s_tuple) ('hello', ' ', 'world') print(s_like_tuple) hello world
4.面向对象模板拼接
from string import Template s = Template('${s1} ${s2}!') print(s.safe_substitute(s1='hello', s2='world')) hello world!
5.常用的+
str_1 = 'hello world!' str_2 = 'my name is python' print(str_1 + str_2) hello world!my name is python
6.join 方法拼接
str_list = ['hello', 'world!'] str_join1 = ' '.join(str_list) str_join2 = '_'.join(str_list) print(str_join1) hello world! print(str_join2) hello_world!
7.f-string方式
name = 'world' myname = 'python_cat' words = f'hello {name}. my name is {myname}' print(words) hello world. my name is python_cat