问题:字符串如何串联?

如何在python中连接字符串?

例如:

Section = 'C_type'

将其与Sec_形成字符串:

Sec_C_type

How to concatenate strings in python?

For example:

Section = 'C_type'

Concatenate it with Sec_ to form the string:

Sec_C_type

回答 0

最简单的方法是

Section = 'Sec_' + Section

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

The easiest way would be

Section = 'Sec_' + Section

But for efficiency, see: https://waymoot.org/home/python_string/


回答 1

您也可以这样做:

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

这样,您不仅可以追加,还可以在字符串中的任意位置插入:

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

you can also do this:

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

This allows you not only append, but also insert wherever in the string:

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

回答 2

只是一条评论,就像有人可能会发现它很有用-您可以一次连接多个字符串:

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

Just a comment, as someone may find it useful – you can concatenate more than one string in one go:

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

回答 3

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

加入():

效率很高,但有点难读。

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

More efficient ways of concatenating strings are:

join():

Very efficent, but a bit hard to read.

>>> Section = 'C_type'  
>>> new_str = ''.join(['Sec_', Section]) # inserting a list of strings 
>>> print new_str 
>>> 'Sec_C_type'

String formatting:

Easy to read and in most cases faster than ‘+’ concatenating

>>> Section = 'C_type'
>>> print 'Sec_%s' % Section
>>> 'Sec_C_type'

回答 4

使用+字符串连接为:

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

Use + for string concatenation as:

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

回答 5

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

参考:http : //www.gidnetwork.com/b-40.html

To concatenate strings in python you use the “+” sign

ref: http://www.gidnetwork.com/b-40.html


回答 6

对于附加到现有字符串末尾的情况:

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

结果是

Sec_C_type

For cases of appending to end of existing string:

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

results in

Sec_C_type

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。