what - Why is the join built-in having no influence on my code?




what is ethereum gas (4)

I had a bug that I reduced down to this:

a = ['a','b','c']
print( "Before", a )
" ".join(a)
print( "After", a )

Which outputs this:

runfile('C:/program.py', wdir=r'C:/')

Before ['a', 'b', 'c']
After ['a', 'b', 'c']

What's going on here?


str.join does not operate in-place because string objects are immutable in Python. Instead, it returns an entirely new string object.

If you want a to reference this new object, you need to explicitly reassign it:

a = " ".join(a)

Demo:

>>> a = ['a','b','c']
>>> print "Before", a
Before ['a', 'b', 'c']
>>> a = " ".join(a)
>>> print "After", a
After a b c
>>>

str.join(<iterable>) returns a str. It doen't mutate the list to a str(!). Do the following,

s = " ".join(list_1)
print(s)

Why doesn't join() turn my list into a string?

''.join(lst_line) does not affect lst_line. It returns a new string. If you want that new string to be called lst_line, you need to assign it back to that variable:

lst_line = ''.join(lst_line)

Notice that this is what the first example does (it just calls it x instead of lst_line).


Why doesn't this join() work?

join() doesn't modify or reassign the list in place, instead it returns the string that it creates:

list_1 = ['a', 'b', 'c']
print (list_1)
list_1_string = ' '.join(list_1)
print (list_1_string)

From the str.join(iterable) docs:

Return a string which is the concatenation of the strings in the iterable iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.