如何在Python中格式化\n换行符

2024-04-24 07:40:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在打印这行代码的输出:

subprocess.check_output('cmd.exe /K cmd',shell=False)

但是输出是这样的

**Microsoft Windows [Version 6.3.9600]\r\n(c) 2013 Microsoft Corporation. All rights reserved.\r\n\r\nC:\\Users\\19leungc8\\Desktop>\r\nC:\\Users\\19leungc8\\Desktop>**

而不是这样:

**Microsoft Windows [Version 6.3.9600]**

**(c) 2013 Microsoft Corporation. All rights reserved.**

如果需要的话,我会提供更多的信息。你知道吗


Tags: 代码cmdoutputversionwindowscheckallusers
2条回答

你不用担心。\nin string表示字符串中的新行。如果您要打印check_output()的内容,您将看到控制台中的\n被替换为新行。例如:

>>> my_text = "1234\n\n1234"
>>> my_text
'1234\n\n1234'
#    ^ value of `my_text` holds `\n`

# on printing the `my_text`, `\n` is replaced with new line
>>> print(my_text)
1234

1234

在你的情况下,你应该这样做:

my_output = subprocess.check_output(...)
print(my_output)

正如^{}的文档所解释的:

By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level.

因此,您得到的是一个bytes对象,它以编码字节的形式包含命令的输出。打印对象时可以看到这一点;无论是打印还是打印repr时,字节文本的引号前面都有一个b

>>> x = b'foo bar'
>>> print(x)
b'foo bar'
>>> x        # basically the same as print(repr(x))
b'foo bar'

为了从中获得正确的字符串,需要使用^{}对bytes对象进行解码。请注意,为了将字节解码为字符串,您需要知道数据的编码方式。通常情况下,这将是utf-8,在这种情况下,您不需要向其传递任何参数:

>>> x.decode()
'foo bar'
>>> print(x.decode())
foo bar

相关问题 更多 >