字符串如何连接?

mic*_*lle 115 python string concatenation

如何在python中连接字符串?

例如:

Section = 'C_type'
Run Code Online (Sandbox Code Playgroud)

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

Sec_C_type
Run Code Online (Sandbox Code Playgroud)

mpe*_*pen 180

最简单的方法是

Section = 'Sec_' + Section
Run Code Online (Sandbox Code Playgroud)

但是为了提高效率,请参阅:https://waymoot.org/home/python_string/

  • 实际上,从您引用的文章开始,它似乎已经过优化.通过timeit的快速测试,我无法重现结果. (8认同)
  • OP要求使用Python 2.4,但是关于版本2.7,Hatem Nassrat已经测试过(2013年7月)[三种连接技术](http://leadsift.com/python-string-concatenation/)其中`+`连接时的速度比15个字符串,但他推荐其他技术:`join`和`%`.(目前的评论只是为了确认@ tonfa上面的评论).干杯;) (3认同)

ryt*_*tis 42

你也可以这样做:

section = "C_type"
new_section = "Sec_%s" % section
Run Code Online (Sandbox Code Playgroud)

这样您不仅可以追加,还可以在字符串中的任何位置插入:

section = "C_type"
new_section = "Sec_%s_blah" % section
Run Code Online (Sandbox Code Playgroud)


Jul*_*usz 29

只是一个评论,因为有人可能会觉得它很有用 - 你可以一次连接多个字符串:

>>> a='rabbit'
>>> b='fox'
>>> print '%s and %s' %(a,b)
rabbit and fox
Run Code Online (Sandbox Code Playgroud)


j7n*_*n7k 24

连接字符串的更有效方法是:

加入():

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

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

字符串格式:

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

>>> Section = 'C_type'
>>> print 'Sec_%s' % Section
>>> 'Sec_C_type'
Run Code Online (Sandbox Code Playgroud)


cod*_*ict 6

使用+字符串连接为:

section = 'C_type'
new_section = 'Sec_' + section
Run Code Online (Sandbox Code Playgroud)