I wonder how to enter a string with a line in Python.

Asked 2 years ago, Updated 2 years ago, 102 views

Python wants to receive string input via raw_input(). However, the input string contains several lines.

For example, the following is the example.

string = raw_input("hex code : ")

Input string

01 | string1

02 | string 2

03 | string 3

...

25 | string25

It's like this.

If you do the output here, even if you try to debug it, the string only has a string called 00|string1.

My guess is 00|string1\n01|string2... It's like this.

So, how to erase the opening text doesn't work.

One of the ways I found it was to write raw_input() several times. However, I don't know how many lines I'll get, so it's ambiguous to write.

string1 = raw_input()
string2 = raw_input()
string3 = raw_input()
...
string25 = raw_input()

Using this method, each string variable has a string entered in a line. However, as I said before, I don't know how many lines will be entered, so it's ambiguous to write.

Is there a special way to erase the line when you receive the input?

I think the most ideal way is to enter a string for each list. It doesn't have to be this way. (string[0] = 01|string1, string[1] = 02|string2....)

import sys
string = sys.stdin.readlines()

If you receive it in the above way, you will be able to receive input by marking up to '\n'. I'm a little reluctant because I have to press Ctrl+d instead of Enter to end the input.

python python-2.7 string raw_input

2022-09-22 08:24

1 Answers

raw_input can only be read one line.

You can get multiple lines through the repeat sentence. If you type enter without entering anything, the input ends.

string = []

while True:
    input_str = raw_input(">")
    if input_str == "":
        break
    else:
        string.append(input_str)

for line in string:
    print line


2022-09-22 08:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.