简体   繁体   English

输出 f.read(20) 时如何查看 '\\n' 字符?

[英]How to see '\n' characters when outputting f.read(20)?

If I print f.readlines(), I am able to see the '\\n' characters included, ['\\n', 'Avoid touching eyes, nose and mouth\\n', '\\n', 'Why? .....]如果我打印 f.readlines(),我可以看到包含的 '\\n' 字符、 ['\\n', 'Avoid touching eyes, nose and mouth\\n', '\\n', 'Why? .....] ['\\n', 'Avoid touching eyes, nose and mouth\\n', '\\n', 'Why? .....]

something like f.read(20) produces:类似 f.read(20) 的东西产生:

Avoid touching eyes

which converts the '\\n' into actual empty line.它将 '\\n' 转换为实际的空行。

How to see actual '\\n' included within f.read(20)如何查看 f.read(20) 中包含的实际 '\\n'

Thank you.谢谢你。

Use the repr() function to get the literal representation of a string, rather than interpreting the control characters.使用repr()函数获取字符串的文字表示,而不是解释控制字符。

print(repr(f.read(20)))

repr() shows what you would have to type as a string literal in a program, so it also puts quotes around the output. repr()显示您必须在程序中作为字符串文字输入的内容,因此它还在输出周围加上引号。

When you print a list, it prints the literal representations of all the list elements.当您打印列表时,它会打印所有列表元素的文字表示。 But when you print a string, it interprets the control characters.但是当你打印一个字符串时,它会解释控制字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM