Concatenating Strings

It’s just occured to me that I don’t know how to this in python and I’ll probably need this soon can anyone help.

Thanks

Paul

you can use string1 = string2 + string3 if its a single operation,

but if you’re doing it often, its better to use string.join or
string1 = “Hello %s” % string2

I think you’d be best off by taking a quick python introduction where all these basic operations are explained.

I came across this page when looking for the same thing

http://www.python.org/doc/essays/list2str.html

Basically, two guys did some experimenting on the fastest way to create strings from a list of ascii values. Its probably way more than you need but they go through different ways of doing it. The best one they found was:

import array
    def f7(list):
        return array.array('B', list).tostring()

But arrays constrains the type of values that can be put into them. (look at http://docs.python.org/lib/module-array.html for array documentation) Also, it does the ascii conversion that you may not need.

My best suggestion is to create a list and append string values to the list. Then use an empty string and the join() method on the list.

MAX_NUM = 1E6
list = []
for i in range(MAX_NUM):
    list.append(str(i))

string = "".join(list)
print string

you can create the list any way you want, this was just to give an idea of how it goes

ewww

the easiest way by far to concatenate strings in python is with the “+” operator.

For example, lets say you want to load a random sound from a list of sounds called sound1.mp3, sound2.mp3, and sound3.mp3. Yes, you could put these in a dictionary, or a list, or you could just do this:

num = randint(1,3)
mySound = loader.loadSfx(“sound” + str(num) )

This concatenates num (which is typecast as a string) to the string “sound” to give you “sound1”, “sound2”, or “sound3”

I’m pretty sure you can use this with regular strings as well, such as:

myHello = "hello " + “world”

good luck

-Adam

Thanks for all the input guys.

trouble is… using the + methode is very slow, if used in a loop over many such operations, it slows the program down. So the other methodes are preffered.

  • string.join(“blah”)
  • s = “blah %s” % string

Your first option would be the best, just one of pythons pitfalls…

Right. If all you want to do is connect two strings together, using the “+” operator is the easiest and most readable way. However, I was was offering an alternative such that repeated concatenation (reading from a file, nested loops, etc) would not be costly. When using the “+” operator, you create a new string each time you use it. Doing this 100 times, means you now have recreate 100 new strings which requires reallocation of memory. Go to python.org to read more about how it works.

Again, it is all in what you really need. If its just “a” + “b” then straight concatenation would probably be best.