如何连接字符串?
- 2025-03-04 08:25:00
- admin 原创
- 41
问题描述:
如何在 python 中连接字符串?
例如:
Section = 'C_type'
将其与Sec_
以下字符串连接起来:
Sec_C_type
另请参阅:如何将变量的值放入字符串中(将其插入字符串中)?以了解更复杂的情况。
解决方案 1:
最简单的方法是
Section = 'Sec_' + Section
但为了提高效率,请参阅:https://waymoot.org/home/python_string/
解决方案 2:
你也可以这样做:
section = "C_type"
new_section = "Sec_%s" % section
这样,您不仅可以附加,还可以插入字符串中的任何位置:
section = "C_type"
new_section = "Sec_%s_blah" % section
解决方案 3:
只是一个评论,因为有人可能会发现它很有用 - 您可以一次连接多个字符串:
>>> a='rabbit'
>>> b='fox'
>>> print '%s and %s' %(a,b)
rabbit and fox
解决方案 4:
连接字符串的更有效的方法是:
加入():
非常高效,但是有点难读。
>>> 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'
解决方案 5:
用于+
字符串连接,如下所示:
section = 'C_type'
new_section = 'Sec_' + section
解决方案 6:
要在 Python 中连接字符串,请使用“+”符号
参考: http: //www.gidnetwork.com/b-40.html
解决方案 7:
对于附加到现有字符串末尾的情况:
string = "Sec_"
string += "C_type"
print(string)
结果是
Sec_C_type
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD