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/
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)
使用+字符串连接为:
section = 'C_type'
new_section = 'Sec_' + section
Run Code Online (Sandbox Code Playgroud)