python拼接字符串的方法有哪些?

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

1.跟ruby类似

deffunc(a):
b='hello'
returnf'{b},{a}'

>>>func("bbb")
'hello,bbb'

这样是不是很干净,跟ruby很类似。

2.print

>>>a='111'
>>>print(f'hello,{a}')
hello,111

3. 使用template

>>>fromstringimportTemplate
>>>t=Template('Hello,$a!')
>>>t.substitute(a='world')
'Hello,world!'

4.直接连接中间有无空格均可

print('hello''world')
print('hello''world')

5.使用%操作符

Python 2.6 以前,% 操作符是唯一一种格式化字符串的方法,它也可以用于连接字符串。

print('%s%s'%('hello','world'))
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。