如何在Python 3.4中将多个变量放在一行(如c scanf)?

时间:2017-01-26 15:25:29

标签: python python-3.x input

喜欢C

int a,b,c; 
scanf("%d %d %d",&a,&b,&c);

如何在python 3.4中使用多个变量

2 个答案:

答案 0 :(得分:2)

Python没有C语言scanf()的等价物。相反,您必须自己将收到的用户输入解析为变量。

Python提供了几种实现此功能的工具。在您的情况下,一种方法是要求用户输入 n ,空格分隔的字符串。然后,您可以将字符串拆分为列表,将每个元素转换为整数,并将列表解压缩为 n 变量。

这是一个使用三个整数的简短演示:

>>> # For the sake of clarity, I do not include
>>> # any error handling in this code.
>>>
>>> ints = input()
12 34 57
>>> a, b, c = [int(n) for n in ints.split()]
>>> a
12
>>> b
34
>>> c
57
>>> 

答案 1 :(得分:0)

如果您只有编号,则可以使用正则表达式

让你的输入是" 12,13,47,89,14"

input = "12 13 47 89 14"
parsed_args = map(int, re.findall("\d+",input))

输出

  

[12,13,47,89,14]