How can strings be concatenated?

467,718

Solution 1

The easiest way would be

Section = 'Sec_' + Section

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

Solution 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

Solution 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

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

Solution 5

Use + for string concatenation as:

section = 'C_type'
new_section = 'Sec_' + section
Share:
467,718
Admin
Author by

Admin

Updated on May 24, 2020

Comments

  • Admin
    Admin almost 4 years

    How to concatenate strings in python?

    For example:

    Section = 'C_type'
    

    Concatenate it with Sec_ to form the string:

    Sec_C_type
    
  • tonfa
    tonfa almost 13 years
    Actually it seems to have been optimized since the article you cite. From a quick test with timeit, I wasn't able to reproduce the results.
  • oHo
    oHo over 10 years
    The OP asked for Python 2.4 but about version 2.7, Hatem Nassrat has tested (July 2013) three concatenation techniques where + is faster when concatenating less than 15 strings but he recommends the other techniques: joinand %. (this current comment is just to confirm the @tonfa's comment above). Cheers ;)
  • pyCthon
    pyCthon over 10 years
    What happens if you want a multi line string concatenation?
  • mpen
    mpen over 10 years
    @pyCthon: Huh? You can put a line break in a string using \n or you can do a line continuation in Python by putting a \ at the end of the line.
  • enthusiasticgeek
    enthusiasticgeek over 9 years
    Seems like join is the fastest and efficient too waymoot.org/home/python_string
  • aland
    aland over 5 years
    This method also allows you to 'concat' an int to string, which isn't possible directly with + (requires wrapping the int in a str())