如何在 python 中由任意数量的空格和换行符分隔时接受用户输入



我一直在尝试采用由任意数量的空格或换行符分隔的整数输入。我知道如何获取空格分隔的输出和具有换行符的输出。在基于 C 的语言中,我们不必关心输入的位置,它在找到时会自动接受输入,但我认为 Python 不是这种情况(如果我错了,请纠正我(。有人可以帮忙吗?

我尝试使用 While 语句直到 True 并在其中使用 try 语句。但它不起作用。

a = []
try:
    while(True):
        a.append(int(input()))
except:
    pass
print(a) 

当我输入时 12 12 12 它返回一个空列表。如果我删除输入中的 int,它会返回一个列表[12 12, 12] .

试试这个: 最短的可能方式

a = []
s=input()
while s != '':  
    i = s.split()       
    [a.append(int(j)) for j in i]
    s=input()
print(a)

输入:

1 2 3
4 5
6

输出:

[1, 2, 3, 4, 5, 6]

您也可以尝试:

a = []
s=input()
while s != '':  
    i = s.split()       
    a.extend(map(lambda s: int(s),i))
    s=input()
print(a)

等等,所以我想我现在明白了。您想接受任意数量的输入,但保存每个由空格分隔的输入作为自己的条目? 实际上有一个字符串方法。下面是它的示例脚本。这不是最好的,但它很好地演示了该方法。

list = []
string = "user input goes here"
splitString = string.split()
for word in splitString:
    list.append(word)
print(list)

输出:

["user", "input", "goes", "here"]

string.split(( 方法默认使用空格,但您可以指定另一个分隔符,如 # 符号。

List = []
String = "Hi#my#name#is#bob"
newString = String.split("#")
for word in newString:
    list.append(word)

编辑:这是一个完整的工作实现,无论分隔两个输入的东西是空格,换行符还是您想要的任何其他内容,它都可以工作。

import re
list = []
while True:
    string = input()
    if string == "break":
        break
    splitString = re.split("[s | rn]", string)
    for word in splitString:
        list.append(word)
    cleanList = []
    for word in list:
        if word != '':
            cleanList.append(word)
print(cleanList)

输入:

12 94 17
56
3

输出:

[12, 94, 17, 56, 3]

功能证明:点击这里

希望你能在这个例子中有一些见解,并添加了我对如何编码的个人观点。

首先,使用多空格输入是可以理解的,但不是多行。更喜欢一个接一个地输入。

出于测试和调试目的,最好单独收集用户和处理输入数据。

现在,假设您已经收集了用户输入并使用 raw_input 存储为数据,这在您需要收集多行输入时很方便。请浏览raw_input,它在 Python3 和 Python2 中受支持。

>>>
>>> data = '''12
...
... 12       12
...
...
... 12'''
>>> data
'12 nn12       12nnn12'
>>> print(data)
12
12       12

12

步骤1:清除所有行分隔

>>> double_spaces = '  '
>>> single_space = ' ' 
>>> data = data.strip().replace('n', single_space)
>>> data
'12   12       12   12'

步骤 2:修复多个空格

>>> while double_spaces in data:
...     data = data.replace(double_spaces, single_space)
...
>>> data
'12 12 12 12'
>>> print(list(map(int, data.split()))
...
... )
[12, 12, 12, 12]
>>>

代码问题

>>> a = []
>>> try:
...     while(True):
...         a.append(int(input()))
... except:
...     pass
...
12
1
12  12
>>> a
[12, 1]
>>>

当您输入12 12 时,应该会发生以下情况。

>>> int('12 12')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12 12'

由于此代码的异常处理except:错误,因此您的用例按预期返回空列表。

由于我更改了输入,因此您会看到这种差异。

最新更新