1

So lets say I have a sentence read from a file:

hello what is your name
my name is david

I am trying to make a list of strings from this so it looks like:

['hello','what','is','your','name','my','name','is','david']

The main problem is when I use the split option, I can only specify one parameter to split the string by.

I end up with either

['hello what is your name','my name is david']

When splitting by '\n'

OR

['hello','what','is','your','name\n','my','name','is','david\n']

When splitting by 'spacebar'.

Is there a way I can combine both these parameters to produce the list of strings above these two?

Thanks.

1
  • Don't specify any parameter: split() Commented Apr 18, 2014 at 6:59

2 Answers 2

7

Just use text.split(), it will split the string by space, tab, and new line.

text = """hello what is your name
my name is david"""
print text.split()

#output: ['hello', 'what', 'is', 'your', 'name', 'my', 'name', 'is', 'david']
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this. It turns out the problem all along was that I used text.split(' ') to specify spacebar. But text.split() splits everything. I had a feeling the answer I needed was dead simple.
0
phrase = """hello what is your name
my name is david"""
l = [word.replace('\n', '') for word in phrase.split()]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.