字符串如何拼接?

119
如何在Python中连接字符串?
例如:
Section = 'C_type'

将其与Sec_连接起来以形成字符串:

Sec_C_type
7个回答

184

8
根据你提到的文章,事实上它似乎已经进行了优化。通过使用timeit进行快速测试,我无法复现结果。 - tonfa
3
楼主要求Python 2.4版本,但是关于2.7版本,Hatem Nassrat在2013年7月测试了三种连接技术,其中当连接少于15个字符串时,“+”比较快,但他推荐使用其他技术:join%。(这个评论只是为了确认上面@tonfa的评论)。干杯;) - oHo
如果您想要进行多行字符串连接,会发生什么? - pyCthon
@pyCthon:什么?你可以使用\n在字符串中换行,或者在Python中通过在行末加上\来进行行连续。 - mpen

44

您也可以这样做:

section = "C_type"
new_section = "Sec_%s" % section

这不仅允许你添加到字符串的末尾,还可以在任意位置插入:

section = "C_type"
new_section = "Sec_%s_blah" % section

这种方法还允许您将int“连接”到字符串,这是直接使用+不可能实现的(需要将int包装在str()中)。 - aland

29

仅作为一条评论,或许有人会发现它有用 - 你可以一次性连接多个字符串:

>>> a='rabbit'
>>> b='fox'
>>> print '%s and %s' %(a,b)
rabbit and fox

24

更高效的字符串连接方法包括:

join():

非常高效,但有点难以阅读。

>>> Section = 'C_type'  
>>> new_str = ''.join(['Sec_', Section]) # inserting a list of strings 
>>> print new_str 
>>> 'Sec_C_type'

字符串格式化:

易于阅读,在大多数情况下比“+”连接更快。

>>> Section = 'C_type'
>>> print 'Sec_%s' % Section
>>> 'Sec_C_type'

似乎join是最快和最有效的方法 http://waymoot.org/home/python_string/ - enthusiasticgeek

6

使用+进行字符串拼接,例如:

section = 'C_type'
new_section = 'Sec_' + section

4

2

对于要追加到现有字符串结尾的情况:

string = "Sec_"
string += "C_type"
print(string)

导致
Sec_C_type

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接