1、使用+ 号在字符串中添加变量
a = 'aa'
print(a + 'bb' + a + a)
输出
aabbaaaa
变量a只能是字符串,如果是别的数据类型需要使用str()转换
a = 23
print('abc' + str(a))
输出
abc23
2、 使用 % 在字符串外 %(变量)
a = ['aa',23]
print('ccc%s%s' % (a,a))
输出
ccc['aa', 23]['aa', 23]
变量是什么类型都可以使用
3、 使用.format()函数
a = {'a':4, 'b':5}
b =[2]
c = 'boring'
print('This {2} is{1} so {0}'.format(c,b,a))
输出
This {'a': 4, 'b': 5} is [2] so boring
还可以这样写
a = {'a': 4, 'b':5}
b =[2]
c = 'boring'
print('This {a} is {b} so {c}'.format(a = c,b = b,c = a))
输出
This boring is [2] so {'a': 4, 'b': 5}
也可以不按照指定位置,按照默认顺序
print('{}{}{}'.format('hello ','world','!'))
输出
hello world!