文章目录
引言
- 引言
- 用法
- +😀
- f-strings😀
- join😀
- format😐
- %😐
- 总结
本文通过实例展示 Python 字符串拼接最常用的五种方法。
用法 +😀>>> a = 'hello'
>>> b = 'world'
>>> c = a + b
>>> c
'helloworld'
>>> a += b
>>> a
'helloworld'
f-strings😀
>>> a = 'hello'
>>> b = 'world'
>>> c = f'{a} {b}'
>>> c
'hello world'
join😀
>>> a = 'hello'
>>> b = 'world'
>>> c = ','.join([a, b])
>>> c
'hello,world'
>>> d = '-'.join([a, b])
>>> d
'hello-world'
format😐
>>> a = 'hello'
>>> b = 'world'
>>> c = '{a} {b}'.format(a=a, b=b)
>>> c
'hello world'
%😐
符号类型%s字符串%d整数%f浮点数
>>> a = 3
>>> b = 2
>>> c = 1.5
>>> d = '%d / %d = %.1f' % (a, b, c)
>>> d
'3 / 2 = 1.5'
总结
+
:最常用的拼接方法,适合字符串变量的简单拼接f-strings
:最灵活、方便的拼接方法,适合字符串变量及常量的复杂拼接join
:适合字符串列表的拼接format
:不推荐使用,可以用f-strings
替代%
:适合熟悉 C 语言的用户使用