How do I read multiple lines of raw input in Python?

后端 未结 9 1421
礼貌的吻别
礼貌的吻别 2020-11-22 09:28

I want to create a Python program which takes in multiple lines of user input. For example:

This is a multilined inp         


        
相关标签:
9条回答
  • 2020-11-22 09:47

    Its the best way for writing the code in python >3.5 version

    a= int(input())
    if a:
        list1.append(a)
    else:
        break
    

    even if you want to put a limit for the number of values you can go like

    while s>0:
    a= int(input())
    if a:
        list1.append(a)
    else:
        break
    s=s-1
    
    0 讨论(0)
  • 2020-11-22 09:57

    Try this

    import sys
    
    lines = sys.stdin.read().splitlines()
    
    print(lines)
    

    INPUT:

    1

    2

    3

    4

    OUTPUT: ['1', '2', '3', '4']

    0 讨论(0)
  • 2020-11-22 10:01

    Just extending this answer https://stackoverflow.com/a/11664652/4476612 instead of any stop word you can just check whether a line is there or not

    content = []
    while True:
        line = raw_input()
        if line:
            content.append(line)
        else:
            break
    

    you will get the lines in a list and then join with \n to get in your format.

    print '\n'.join(content)
    
    0 讨论(0)
  • 2020-11-22 10:03

    The easiest way to read multiple lines from a prompt/console when you know exact number of lines you want your python to read, is list comprehension.

    lists = [ input() for i in range(2)]

    The code above reads 2 lines. And save inputs in a list.

    0 讨论(0)
  • 2020-11-22 10:09

    sys.stdin.read() can be used to take multiline input from user. For example

    >>> import sys
    >>> data = sys.stdin.read()
      line one
      line two
      line three
      <<Ctrl+d>>
    >>> for line in data.split(sep='\n'):
      print(line)
    
    o/p:line one
        line two
        line three
    
    0 讨论(0)
  • 2020-11-22 10:11

    Alternatively,You can try sys.stdin.read()

    import sys
    s = sys.stdin.read()
    print(s)
    
    0 讨论(0)
提交回复
热议问题