How to read formatted input in python?

前端 未结 4 711
再見小時候
再見小時候 2021-01-05 03:49

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

3, 4, 5, 1, 8

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

How do I do this in python?

相关标签:
4条回答
  • 2021-01-05 03:55

    Under Python 2.x only (*)

    after a = input()

    a is a tuple with the 5 values readily parsed!

    A quick way to assign these 5 values is

    a, b, c, d, e = a
    

    (*) with Python version 3.0? or for sure 3.1, input() works more like the raw_input() method of 2.x, which makes it less confusing. (thank you mshsayem to point this out!)

    0 讨论(0)
  • 2021-01-05 03:59
    in = eval(input())
    
    a, b, c, d, e = in
    
    0 讨论(0)
  • 2021-01-05 04:06

    If you print out a (the variable containing your input) you will find out, that a already contains a tuple. You do not have to split the contents.

    >>> a = input()
    3, 4, 5, 1, 8
    >>> print(a)
    (3, 4, 5, 1, 8)
    >>> type(a)
    <type 'tuple'>
    >>> a[0]
    3
    >>> len(a)
    5

    0 讨论(0)
  • 2021-01-05 04:21

    Use raw_input() instead of 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']
    

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

    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.

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

    Two more things:

    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.

    Unpacking:

    >>> l = (1,2,3,4,5)
    >>> a,b,c,d,e = l
    >>> e
    5
    
    0 讨论(0)
提交回复
热议问题