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

后端 未结 9 1422
礼貌的吻别
礼貌的吻别 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 10:12

    Keep reading lines until the user enters an empty line (or change stopword to something else)

    text = ""
    stopword = ""
    while True:
        line = raw_input()
        if line.strip() == stopword:
            break
        text += "%s\n" % line
    print text
    
    0 讨论(0)
  • 2020-11-22 10:13
    sentinel = '' # ends when this string is seen
    for line in iter(raw_input, sentinel):
        pass # do things here
    

    To get every line as a string you can do:

    '\n'.join(iter(raw_input, sentinel))
    

    Python 3:

    '\n'.join(iter(input, sentinel))
    
    0 讨论(0)
  • 2020-11-22 10:13

    *I struggled with this question myself for such a long time, because I wanted to find a way to read multiple lines of user input without the user having to terminate it with Control D (or a stop word). In the end i found a way in Python3, using the pyperclip module (which you'll have to install using pip install) Following is an example that takes a list of IPs *

    import pyperclip
    
    lines = 0
    
    while True:
        lines = lines + 1 #counts iterations of the while loop.
    
        text = pyperclip.paste()
        linecount = text.count('\n')+1 #counts lines in clipboard content.
    
        if lines <= linecount: # aslong as the while loop hasn't iterated as many times as there are lines in the clipboard.
            ipaddress = input()
            print(ipaddress)
    
        else:
            break
    

    For me this does exactly what I was looking for; take multiple lines of input, do the actions that are needed (here a simple print) and then break the loop when the last line was handled. Hope it can be equally helpful to you too.

    0 讨论(0)
提交回复
热议问题