Home > Back-end >  .join() gives back list as a result in python
.join() gives back list as a result in python

Time:07-29

Could someone, please, explain why .join() behaves in the following way:

input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join(str(input))
print(a)

And the result is:

[ 1 ,   0 ,   5 ,   3 ,   4 ,   1 2 ,   1 9 ]

Not only is there still a list, but also an additional space. How come? When I use map() it works:

a = " ".join(list(map(str, input)))

But I would like to know what is wrong with the .join method I'm using.

CodePudding user response:

str(input) returns one string '[1, 0, 5, 3, 4, 12, 19]', so then join uses each character of the string as input (a string is an iterable, like a list), effectively adding a space between each.

The effect is more visible if we join with a -: '[-1-,- -0-,- -5-,- -3-,- -4-,- -1-2-,- -1-9-]'

In contrast, list(map(str, input)) converts each number to string, giving a list of strings (['1', '0', '5', '3', '4', '12', '19']), which join then converts to '1 0 5 3 4 12 19'

CodePudding user response:

See @mozway's answer to understand .join()'s behavior.

To get what you want (using join), you should try this:

input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join([str(i) for i in input])
print(a)

Output:

1 0 5 3 4 12 19
  • Related