Reputation: 15
Essentially I want each new word from the user input to be on the next line, so a sentence such as: "Hello World" would appear as
"Hello"
"World"
Here is my current script:
EnterString = input("Enter the first word of your sentence ")
e =(EnterString)
e2 =(e.split(" "))
print (e2)
Which would give the result:
['Hello', 'world']
How can I make Python detect the spaces and align the words accordingly?
Thanks in advance.
Upvotes: 0
Views: 1389
Reputation:
Judging by your print
syntax as well as the fact that you are using input
and not raw_input
, I believe this is Python 3.x. If so, then you can just do this:
print(*e2, sep="\n")
See a demonstration below:
>>> EnterString = input("Enter the first word of your sentence ")
Enter the first word of your sentence Hello world
>>> e = EnterString
>>> e2 = e.split()
>>> print(*e2, sep="\n")
Hello
world
>>>
Here is a reference on what the *
is.
Also, str.split
defaults to split on whitespace. So, all you need is e.split()
.
However, if you are in fact on Python 2.x (namely, Python 2.7), then you will also need to put this line at the top of your script:
from __future__ import print_function
The above will make print
like it is in Python 3.x, allowing you to use it as I demonstrated.
Upvotes: 0
Reputation: 19556
When you split the input on spaces, you get your list of each "new" word.
You can then print out each one using a loop.
for word in e2:
print(word)
Upvotes: 2