如何在Python中打印字符串,并将新行字符翻译成实际的新行?

时间:2016-03-18 21:07:42

标签: python string printing

我已经多次看到了这种情况的反面。我正在使用子进程的输出,当我打印输出时,它会显示\ n而不是实际进入下一行。

out = subprocess(...)
print (out)

output >> 
some\ntext\nhere

我需要的是

output >>
some
text
here

编辑:“out”包含\ r的\ n和\ t的组合。

2 个答案:

答案 0 :(得分:1)

我相信你的文字是原始编码的。尝试底部的replace方法,看看是否有效。

# Works fine for string.
out = 'some\ntext\nhere'

>>> print(out)
some
text
here

# Works fine for unicode.
out = u'some\ntext\nhere'

>>> print(out)
some
text
here

>>> repr(out)
"u'some\\ntext\\nhere'"

# Doesn't work for raw.
out = r'some\ntext\nhere'

>>> print(out)
some\ntext\nhere

>>> repr(out)
"'some\\\\ntext\\\\nhere'"

# Try this.
print(out.replace('\\n', '\n'))
some
text
here

答案 1 :(得分:0)

out = out.split('\n')
for val in out:
    print(val)

输出:

some
text
here

如果你有\ r和\ t以及

out = 'some\rtext\nhere'
result = []
temp_str = ''
for val in out:
    if val.isalpha():
        temp_str+=val
    else:
        result.append(temp_str)
        temp_str = ''
if temp_str:
    result.append(temp_str)
for val in result:
    print(val)

输出:

some
text
here