python
python

Reputation: 1940

Strings and appending in Python

In Python a string is immutable. I find the function string.join() could add the value to a string but it seems the following doesn't work.

#coding: utf-8
if __name__ == "__main__":
    str = "A fox has jumped into the river"
    tmp = ""
    for i in str:
        tmp = tmp.join(i)
    print tmp

I expect the output should be "A fox has jumped into the river", but it output the "r" why?

Is there any similar methods which is something like string.append()?

Upvotes: 0

Views: 575

Answers (4)

jamylak
jamylak

Reputation: 133764

>>> '-'.join('a')
'a'

str.join doesn't work like that. That's the reason why "r" is the output, since at the end of the for loop you have set tmp = tmp.join('r') whichc will just result in "r".

This is how str.join is usually used:

>>> '-'.join('abc')
'a-b-c'

or

>>> ', '.join(['foo', 'bar', 'spam'])
'foo, bar, spam'

You want simple string concatenation

tmp = ""
for i in str:
    tmp += i

or use a list and ''.join for efficient string concatenation (the former solution is O(N^2) due to the immutable nature of strings)

tmp = []
for i in str:
    tmp.append(i)
tmp = ''.join(tmp)

(''.join joins the list into a string with an empty string as a separator)

One last note: don't use str as a variable name, it's a built-in.

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1124988

You can append simply by using +:

tmp = tmp + i

which can be combined with an in-place addition assignment:

tmp += i

but this is not nearly as efficient as joining the whole sequence with ''.join():

str = "A fox has jumped into the river"
tmp = ''.join(str)

The latter is of course, rather pointless, as we just took all individual characters of str, and rejoined them into a new, otherwise equal, string. But it is far more efficient than calling + in a loop, as .join() only has to create a new string once, while a loop with + creates new strings for each concatenation.

It gets more interesting when you use a delimiter:

>>> ' - '.join(str)
'A -   - f - o - x -   - h - a - s -   - j - u - m - p - e - d -   - i - n - t - o -   - t - h - e -   - r - i - v - e - r'

The thing to note here is that you call .join() on the delimiter string, not on the sequence you are about to join!

Upvotes: 3

pypat
pypat

Reputation: 1116

This will do what you want i think:

if __name__ == "__main__":
    str = "A fox has jumped into the river"
    tmp = ""
    for i in str:
        tmp += i
    print (tmp)

The reason you code doesn't work is that join joins all the tokens in the list you are providing, seperated by whatever string you "apply" it to. It doesn't actually append to a string.

Upvotes: 1

jeyraof
jeyraof

Reputation: 893

>>> a = "pp"
>>> b = "kk"
>>> a += b
>>> a
'ppkk'

Upvotes: 4

Related Questions