Reputation: 418
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)']
Upvotes: 0
Views: 78
Reputation: 4449
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.
Upvotes: 1
Reputation: 782574
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.
Upvotes: 1