Home > OS >  string .join method confusion
string .join method confusion

Time:01-27

I tried to join a sample string in two 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)

K

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)']

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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)')
  • Related