如何使用 python 中的换行符读取用户输入,并打印为换行符?

How can I read userinput with the newline in python, that prints as a new line?

我想将用户输入读取为字符串,其行为就好像我是这样分配的:

my_string = "line1\r\nline2"

如果我打印这个,它会创建两行。我无法读取用户输入,其行为方式相同,无论是使用 input() 还是 sys.stdin.read().

>>> buffer = input()
line1\r\nline2
>>> print(buffer)
line1\r\nline2
>>> print("line1\r\nline2")
line1
line2
>>>

编辑:我不想阅读多行,我想阅读包含新行转义序列并打印为两行的一行。

您可以将字符串编码为字节,然后使用 unicode_escape 编码对字节进行解码:

>>> buffer = input()
line1\r\nline2
>>> print(buffer.encode().decode('unicode_escape'))
line1
line2