2

I'm just wondering why

'hello world'.split('world')

also returns an empty string '' in the list

['hello ','']

while it splits perfectly for

'hello world people'.split('world')

into the list

['hello ',' people']
0

2 Answers 2

2

The .split function separates the string by what is in the brackets and what os on the brackets is omitted from the string. Therefore, your results are completely correct.

If you want to split by words, do:

'hello world people'.split()

This splits by a space and therefore returns:

['hello','world','people']
Sign up to request clarification or add additional context in comments.

Comments

0

Method s.split(X) essentially "removes" each instance of X from s and returns a list of "leftovers." When you remove "world" from "Hello world", you get "hello " in front of it and an empty string "" after it. And that's what you got.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.