How can strings be concatenated?

How to concatenate strings in python?

For example:

Section = 'C_type'

Concatenate it with Sec_ to form the string:

Sec_C_type

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The easiest way would be

Section = 'Sec_' + Section

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

Method 2

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

Method 3

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

Method 4

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'

Method 5

Use + for string concatenation as:

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

Method 6

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

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

Method 7

For cases of appending to end of existing string:

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

results in

Sec_C_type


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x