119

How to concatenate strings in python?

For example:

Section = 'C_type'

Concatenate it with Sec_ to form the string:

Sec_C_type
martineau
  • 119,623
  • 25
  • 170
  • 301
michelle
  • 1,241
  • 2
  • 8
  • 4

7 Answers7

184

The easiest way would be

Section = 'Sec_' + Section

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

Graham
  • 3,153
  • 3
  • 16
  • 31
mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • 8
    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. – tonfa May 28 '11 at 15:05
  • 3
    The OP asked for Python 2.4 but about version 2.7, Hatem Nassrat has tested (July 2013) [three concatenation techniques](http://leadsift.com/python-string-concatenation/) where `+` is faster when concatenating less than 15 strings but he recommends the other techniques: `join`and `%`. (this current comment is just to confirm the @tonfa's comment above). Cheers ;) – oHo Nov 12 '13 at 13:06
  • What happens if you want a multi line string concatenation? – pyCthon Nov 28 '13 at 19:52
  • @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. – mpen Nov 28 '13 at 20:45
44

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
rytis
  • 2,649
  • 22
  • 27
  • This method also allows you to 'concat' an int to string, which isn't possible directly with `+` (requires wrapping the int in a `str()`) – aland Dec 08 '18 at 16:04
29

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
Juliusz
  • 2,096
  • 2
  • 27
  • 32
24

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'
avelis
  • 1,143
  • 1
  • 9
  • 18
j7nn7k
  • 17,995
  • 19
  • 78
  • 88
6

Use + for string concatenation as:

section = 'C_type'
new_section = 'Sec_' + section
codaddict
  • 445,704
  • 82
  • 492
  • 529
4

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

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

Steve Robillard
  • 13,445
  • 3
  • 36
  • 32
2

For cases of appending to end of existing string:

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

results in

Sec_C_type
Tom Howard
  • 4,672
  • 2
  • 43
  • 48