How can strings be concatenated?

PythonStringConcatenation

Python Problem Overview


How to concatenate strings in python?

For example:

Section = 'C_type'

Concatenate it with Sec_ to form the string:

Sec_C_type

Python Solutions


Solution 1 - Python

The easiest way would be

Section = 'Sec_' + Section

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

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

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'

Solution 5 - Python

Use + for string concatenation as:

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

Solution 6 - Python

To concatenate strings in python you use the "+" sign

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

Solution 7 - Python

For cases of appending to end of existing string:

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

results in

Sec_C_type

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmichelleView Question on Stackoverflow
Solution 1 - PythonmpenView Answer on Stackoverflow
Solution 2 - PythonrytisView Answer on Stackoverflow
Solution 3 - PythonJuliuszView Answer on Stackoverflow
Solution 4 - Pythonj7nn7kView Answer on Stackoverflow
Solution 5 - PythoncodaddictView Answer on Stackoverflow
Solution 6 - PythonSteve RobillardView Answer on Stackoverflow
Solution 7 - PythonTom HowardView Answer on Stackoverflow