string .join method confusion

Question:

I tried to join a sample string in three ways, first entered by the code and then entered by user input. I got different results.

#Why isn’t the output the same for these (in python 3.10.6):

sampleString = 'Fred','you need a nap! (your mother)'
ss1 = ' - '.join(sampleString)
print(ss1), print()

sampleString = input('please enter something: ')  #entered 'Fred','you need a nap! (your mother)'
ss2 = ' - '.join(sampleString)
print(ss2)

sampleString = input(['Fred','you need a nap! (your mother)']) 
ss2 = ' - '.join(sampleString)
print(ss2)

output:

Fred - you need a nap! (your mother)

please enter something: 'Fred','you need a nap! (your mother)'
' - F - r - e - d - ' - , - ' - y - o - u -   - n - e - e - d -   - a -   - n - a - p - ! -   - ( - y - o - u - r -   - m - o - t - h - e - r - ) - '

['Fred', 'you need a nap! (your mother)']
Asked By: gerald

||

Answers:

When you do

sampleString = 'Fred','you need a nap! (your mother)'

Because of the comma, sampleString is a tuple containing two strings. When you join it, the delimiter is put between each element of the tuple. So it’s put between the strings Fred and you need a nap! (your mother).

When you do

sampleString = input('please enter something: ')

sampleString is a string. When you join it, the delimiter is put between each element of the string. So it’s put between each character.

You can see this difference if you do print(sampleString) in each case.

Answered By: Barmar

In the first case, sampleString = 'Fred','you need a nap! (your mother)' is a tuple consisting of two strings. When you join them the separator (-) is put between them.

In the second case sampleString is just a str, not a tuple. So the separate is placed between each element (character) of the string.

Answered By: Woodford

The first block of code is joining the elements of the tuple sampleString using the string ‘ – ‘ as a separator. In the second block of code, the user input is being treated as a single string, so the join() method is trying to join the characters of the string using the separator ‘ – ‘. This is why the output is different. If you want the second block of code to produce the same output as the first block, you should change the user input to be a tuple or a list of strings:

sampleString = ('Fred', 'you need a nap! (your mother)')
Answered By: Nova
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.