【发布时间】:2011-02-12 06:51:01
【问题描述】:
如何在python中连接字符串?
例如:
Section = 'C_type'
将其与Sec_ 连接形成字符串:
Sec_C_type
【问题讨论】:
标签: python string concatenation
如何在python中连接字符串?
例如:
Section = 'C_type'
将其与Sec_ 连接形成字符串:
Sec_C_type
【问题讨论】:
标签: python string concatenation
【讨论】:
+ 在连接少于 15 个字符串时更快,但他推荐其他技术:@ 987654325@和%。 (当前的评论只是为了确认上面@tonfa 的评论)。干杯;)
\n 在字符串中添加换行符,也可以在 Python 中通过在行尾添加 \ 来续行。
只是一个评论,因为有人可能会觉得它很有用 - 您可以一次连接多个字符串:
>>> a='rabbit'
>>> b='fox'
>>> print '%s and %s' %(a,b)
rabbit and fox
【讨论】:
更有效的连接字符串的方法是:
加入():
非常有效,但有点难以阅读。
>>> 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'
【讨论】:
对于追加到现有字符串末尾的情况:
string = "Sec_"
string += "C_type"
print(string)
结果
Sec_C_type
【讨论】:
你也可以这样做:
section = "C_type"
new_section = "Sec_%s" % section
这不仅可以让您追加,还可以在字符串中的任何位置插入:
section = "C_type"
new_section = "Sec_%s_blah" % section
【讨论】:
+ 实现(需要将 int 包装在 str() 中)
使用+ 进行字符串连接:
section = 'C_type'
new_section = 'Sec_' + section
【讨论】:
要在 python 中连接字符串,请使用“+”号
【讨论】: