How to interpret result when a string of list is passed into the join() function in Python?

Viewed 44

I was playing around with join function when I mistakenly passed a list converted to string in the join function. The result is very weird as shown in the code below.

What is the best way to interpret the result?

test =  ['2', '1', '3']
s = 'x'
print(s.join(str(test)))

Output

[x'x2x'x,x x'x1x'x,x x'x3x'x]
2 Answers

Basically when you type str(test) python makes a string "['2', '1', '3']". This is a string with 15 characters (don't get confused by the ', these are considered characters too.

Now when you do s.join(str(test)) you can think of it as putting an x between each character of the string.

Originally the sequence of characters was:

[ --> ' --> 2 --> ' --> , --> ' --> 1 --> ' --> , -->' --> 3 --> ' --> ]

Then 'x'.join(str(test)) placed an x everywhere where there is an arrow (-->) above.

The typical use of join would be to pass a list instead of a string as its argument. For example if you wrote:

s.join(test)

It would return:

'2x1x3'

The .join function combines the elements of a list into a string with some delimiter that you define. If you pass it a string though it will split it into a list to then join it with your delimiter. So you passed it your string list which it split to:

'[', "'", '1', "'", ',', ' ', "'", '2', "'", ',', ' ', "'", '3', "'", ']'

and then it joined with the 'x'

Related