Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 604
michelle Avatar asked Apr 26 '10 06:04

michelle


4 Answers

The easiest way would be

Section = 'Sec_' + Section

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

like image 116
mpen Avatar answered Nov 16 '22 00:11

mpen


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
like image 27
rytis Avatar answered Nov 15 '22 22:11

rytis


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
like image 26
Juliusz Avatar answered Nov 16 '22 00:11

Juliusz


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'
like image 22
j7nn7k Avatar answered Nov 16 '22 00:11

j7nn7k