Dewsworld
Dewsworld

Reputation: 14033

Python string concatenation not working as expected

out = 'Hello'
print( out.join([' world']) )

When I run it, it shows

world

Isn't it supposed to print hello world?

Upvotes: 1

Views: 4060

Answers (3)

Matt Alcock
Matt Alcock

Reputation: 12881

join() behaves slightly differently to how you expect. It takes a list of words to join. The seed word is what you put between the joins.

' '.join(['Hello', 'world'])
>> Hello world

','.join(['Hello', 'world'])
>> Hello,world

'/'.join(['name', 'location', 'age'])
>> name/location/age

'*'.join(['name'])
>> name

'hello'.join(['world'])
>> world

Upvotes: 2

user647772
user647772

Reputation:

Since your array contains only one entry " world" there is nothing to join.

Upvotes: 0

Lukáš Lalinský
Lukáš Lalinský

Reputation: 41306

No, it joins the elements of the list with the word 'Hello'. For example, if you had ['A', 'B'], it would produce 'AHelloB'. Since there is only one element in your list, there is nothing to join, so it can just return the only element in there unchanged.

What you wanted is probably something like ' '.join(['Hello', 'world']).

Upvotes: 6

Related Questions