Main index > Python programming > string concatenation

By cs-cam (Desklet Author), on Thu Apr 14 04:33:31 2005: string concatenation.

now i realise this is an incredibly stupid topic, i know. i've google and it gave me info on a couple of different string objects but surely there's something more basic.

Code:


print integer1 + integer2
# now thats math, is it acceptable to do with strings as well? it does work
print string1 + string 2
# or is there a better way?



thanks :)

By syfou (Core Developer & Desklet Author), on Thu Apr 14 12:44:21 2005.

There are many: I suggest you look at the String Services chapter from the official documentation... It depends what you want to do, really. Maybe is it the join() method for the string type you are looking for? Short example:

Code:


str='this is a string to be splitted, than joined back'
print 'Initial string:', repr(str)
print 'Splitted string:', str.split()
print 'Splited than rejoined string:', repr(' '.join(str.split())

By exilejedi (Core Developer & Desklet Author), on Thu Apr 14 22:18:20 2005.

You can join strings together using several different techniques:


Code:

a = 'foo' + 'bar' # join two strings
a = '%s%s' % ('foo','bar') # join two strings using string formatting
a = ''.join(['foo', 'bar']) # join a list of strings


Want to just stick stuff onto the end of a string? You can also do:

Code:

a = 'foo'
a += 'bar'


Using join() and string formatting can be significantly faster to use (you end up constructing fewer "throwaway" strings in the process). You can experiment with the timeit module to see the timing differences. In general it's probably not a big deal, but if you are executing the code very often (in, eg, a busy web site), every little bit helps. In a desklet, though, I'm doubting you are going to squeeze too much marginal performance out of how you choose to concatenate strings. ;-)

By cs-cam (Desklet Author), on Fri Apr 15 02:50:29 2005.

It's not the performance that's my problem, I'm just a picky clown that wants to do things the "right" way. Still learning python so I'm still learning the proper way to do thigns but I'll get there one day, so far it's looking like a pretty decent language.

By exilejedi (Core Developer & Desklet Author), on Fri Apr 15 14:58:13 2005.

In general, the simpler/cleaner it is, the more "Pythonic" it is.

I really didn't like Python much when I started learning it (for my day job)... But five years in, I've found that I really enjoy it, much more than it should be healthy to enjoy a programming language. It's very comfortable and doesn't "get in the way" if that makes sense.


adesklets is proud to be hosted on:

SourceForge.net Logo

Back to adesklets.sf.net.