如何在Python中连接字符串?
例如:
例如:
Section = 'C_type'
将其与Sec_
连接起来以形成字符串:
Sec_C_type
Section = 'C_type'
将其与Sec_
连接起来以形成字符串:
Sec_C_type
您也可以这样做:
section = "C_type"
new_section = "Sec_%s" % section
这不仅允许你添加到字符串的末尾,还可以在任意位置插入:
section = "C_type"
new_section = "Sec_%s_blah" % section
+
不可能实现的(需要将int包装在str()
中)。 - aland仅作为一条评论,或许有人会发现它有用 - 你可以一次性连接多个字符串:
>>> a='rabbit'
>>> b='fox'
>>> print '%s and %s' %(a,b)
rabbit and fox
更高效的字符串连接方法包括:
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'
使用+
进行字符串拼接,例如:
section = 'C_type'
new_section = 'Sec_' + section
对于要追加到现有字符串结尾的情况:
string = "Sec_"
string += "C_type"
print(string)
Sec_C_type
join
和%
。(这个评论只是为了确认上面@tonfa的评论)。干杯;) - oHo\n
在字符串中换行,或者在Python中通过在行末加上\来进行行连续。 - mpen