字符串如何连接?

如何在 python 中连接字符串?

For example:

Section = 'C_type'

Concatenate it with Sec_ to form the string:

Sec_C_type
469233 次浏览

The easiest way would be

Section = 'Sec_' + Section

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

要在 python 中连接字符串,可以使用“ +”符号

档号: http://www.gidnetwork.com/b-40.html

使用 +进行字符串连接:

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

你也可以这样做:

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

这样不仅可以附加,而且可以在字符串的任何位置插入:

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

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

参加() :

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

>>> 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'

只是一个注释,因为有人可能会发现它很有用——你可以一次连接多个字符串:

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

For cases of appending to end of existing string:

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

结果出来了

Sec_C_type