如何在python中读取格式化的输入? [英] How to read formatted input in python?

查看:772
本文介绍了如何在python中读取格式化的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从stdin读取五个输入的数字,如下所示:

I want to read from stdin five numbers entered as follows:

3,4,5,1,8

3, 4, 5, 1, 8

分为单独的变量a,b,c,d& e.

into seperate variables a,b,c,d & e.

我如何在python中做到这一点?

How do I do this in python?

我尝试过:

import string
a=input()
b=a.split(', ')

表示两个整数,但是不起作用.我得到:

for two integers, but it does not work. I get:

Traceback (most recent call last):
  File "C:\Users\Desktop\comb.py", line 3, in <module>
    b=a.split(', ')
AttributeError: 'tuple' object has no attribute 'split'

如何执行此操作?并假设我没有固定数目,而是可变数目的n个整数.然后呢?

How to do this? and suppose I have not a fixed but a variable number n integers. Then?

推荐答案

使用 raw_input() 而不是input().

# Python 2.5.4
>>> a = raw_input()
3, 4, 5
>>> a
'3, 4, 5'
>>> b = a.split(', ')
>>> b
['3', '4', '5']
>>> [s.strip() for s in raw_input().split(",")] # one liner
3, 4, 5
['3', '4', '5']

具有误导性的名称 input 函数不能满足您的要求期待它.它实际上将stdin的输入评估为python代码.

The misleadingly names input function does not do what you'd expect it to. It actually evaluates the input from stdin as python code.

在您的情况下,事实证明,您拥有的只是a中的一个元组,都已解析并可以开始工作,但是通常您并不真正希望使用这种奇怪的副作用.其他输入可能导致任何事情发生.

In your case it turns out that what you then have is a tuple of numbers in a, all parsed and ready for work, but generally you don't really want to use this curious side effect. Other inputs can cause any number of things to happen.

偶然地,他们在Python 3中解决了这个问题,现在 input 函数可以达到您的期望.

Incidentally, in Python 3 they fixed this, and now the input function does what you'd expect.

还有两件事:

  1. 您不需要import string即可进行简单的字符串操作.
  2. 像mjv 所述一样,要将元组或列表拆分为多个变量,可以对其进行解压缩".但是,如果您不知道列表有多长,这将是不可行的.
  1. You don't need to import string to do simple string manipulations.
  2. Like mjv said, to split a tuple or a list into several variables, you can 'unpack' it. This will not be feasible if you don't know how long the list will be, though.

拆箱:

>>> l = (1,2,3,4,5)
>>> a,b,c,d,e = l
>>> e
5

这篇关于如何在python中读取格式化的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆