2

I know that the regular input function can accept single lines, but as soon as you try to write a string paragraph and hit enter for the next line, it terminates. Is there a beginner-friendly way to accept multiline user string inputs as variables?

0

6 Answers 6

3

A common way of doing this in programs is to have an "I'm done" string (e.g. a single period), and to keep reading in lines until the line read matches that string.

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)
Sign up to request clarification or add additional context in comments.

Comments

1

You can do that using sys library

import sys
x = sys.stdin.read()

Comments

0
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

Comments

0
import sys
s = sys.stdin.read()
# print(s) # It will print everything 
for line in s.splitlines(): # to read line by line
    print(line)

1 Comment

While this may address the issue, you also want to provide a way to get out of the loop. Otherwise, this will be an endless multiline user input.
0
[input() for i in range(int(input()))]

for n multiline user inputs, each index in the list will be a new line input from the user.

Comments

-2
Line=""

while True:

    x=input()

    Line=Line+" "+x

    if "." in x:

        break

print(Line)

1 Comment

Line=Line+" "+x is inefficient in Python, it's better to use join. Also, this would stop as soon as a line contains a dot, which could appear in many situations (Well... 3.14?). Finally, it removes the newlines between the inputs...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.