【问题标题】:How to get user input for multiline lines in Python 3?如何在 Python 3 中获取多行行的用户输入?
【发布时间】:2012-10-19 04:47:38
【问题描述】:

我知道常规输入函数可以接受单行,但是一旦您尝试编写字符串段落并按回车键输入下一行,它就会终止。是否有一种适合初学者的方式来接受多行用户字符串输入作为变量?

【问题讨论】:

    标签: python input multiline


    【解决方案1】:
    [input() for i in range(int(input()))]
    

    对于 n 个多行用户输入,列表中的每个索引都是来自用户的新行输入。

    【讨论】:

      【解决方案2】:
      import sys
      s = sys.stdin.read()
      # print(s) # It will print everything 
      for line in s.splitlines(): # to read line by line
          print(line)
      

      【讨论】:

      • 虽然这可能会解决问题,但您还想提供一种摆脱循环的方法。否则,这将是一个无穷无尽的多行用户输入。
      【解决方案3】:
      def processString(x):
          print(x.replace('process','whatever'))
      
      lines = ""
      while True:
          if lines == "":
              lines = ""
              print("Enter string:")
          x = input()
          if x == "" and lines != "":
              processString(lines)
              break
          else:
              lines += x
      
      # then hit enter once after multi-line string to process it
      

      【讨论】:

        【解决方案4】:
        Line=""
        
        while True:
        
            x=input()
        
            Line=Line+" "+x
        
            if "." in x:
        
                break
        
        print(Line)
        

        【讨论】:

          【解决方案5】:

          您可以使用 sys 库来做到这一点

          import sys
          x = sys.stdin.read()
          

          【讨论】:

            【解决方案6】:

            在程序中执行此操作的一种常见方法是使用“I'm done”字符串(例如,单个句点),并继续按行读取,直到读取的行与该字符串匹配。

            print("Enter as many lines of text as you want.")
            print("When you're done, enter a single period on a line by itself.")
            
            buffer = []
            while True:
                print("> ", end="")
                line = input()
                if line == ".":
                    break
                buffer.append(line)
            multiline_string = "\n".join(buffer)
            
            print("You entered...")
            print()
            print(multiline_string)
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-09-06
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-10-17
              • 1970-01-01
              相关资源
              最近更新 更多