如何在Python中打印字符串,并将新行字符转换为实际新行?

如何在Python中打印字符串,并将新行字符转换为实际新行?,python,string,printing,Python,String,Printing,我已经多次看到与此相反的答案。我正在使用子流程的输出,当我打印输出时,它会显示\n而不是实际转到下一行 out = subprocess(...) print (out) output >> some\ntext\nhere 我需要的是 output >> some text here 编辑:“out”包含\r\n和\t的组合 out = out.split('\n') for val in out: print(val) 输出: some text h

我已经多次看到与此相反的答案。我正在使用子流程的输出,当我打印输出时,它会显示\n而不是实际转到下一行

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

output >> 
some\ntext\nhere
我需要的是

output >>
some
text
here
编辑:“out”包含\r\n和\t的组合

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

some
text
here
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
some
text
here

我相信你的文字是原始编码的。尝试底部的
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

什么是
repr(out)
?它实际上是否包含例如
\\n
?谢谢。这是一个很好的解决方案。问题是字符串包含\r和\n以及\t的组合。。。有没有办法处理所有特殊字符?如果没有,我可以接受上面的解决方案。@Arash:更新了我的答案以包括你的情况