[英]How to make text from user input start a new line at every space?
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”的句子将显示为
"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? 如何让Python检测空格并相应地对齐单词?
Thanks in advance. 提前致谢。
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)
使用join方法
print("\n".join(e2))
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. 从
print
语法以及使用input
而不是raw_input
的事实来看,我相信这是Python3.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. 另外,
str.split
默认情况下在空格上分割。 So, all you need is e.split()
. 因此,您只需要
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: 但是,如果您实际上使用的是Python 2.x(即python 2.7),则还需要将此行放在脚本的顶部:
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. 上面的代码将像在Python 3.x中一样进行
print
,使您可以像我演示的那样使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.