简体   繁体   English

Python在两行而不是一行上打印引号

[英]Python Printing Quotation Marks on Two Lines Instead of One

I am reading from an external text file, named 'greeting.txt' where the contents of the text file are simply: 我正在从一个名为'greeting.txt'的外部文本文件中读取,其中文本文件的内容很简单:

HELLO

However, when I attempt to print the contents of the text file enclosed in quotes the terminal prints out: 但是,当我尝试打印用引号引起来的文本文件的内容时,终端将输出:

"HELLO
"

I am using the following code: 我正在使用以下代码:

for line in open('greeting.txt', "r"): print ('"%s"' % line)

I desire the string to be enclosed in quotes printed on the same line. 我希望将字符串括在同一行上打印的引号中。 I have never encountered this problem before despite using Python for similar purposes, any help would be appreciated. 尽管将Python用于类似目的,但我从未遇到过此问题,我们将不胜感激。

The problem is that, what is written in your file is probably Hello\\n and if you read the whole line you are then printing "Hello\\n" which causes the newline to be in front of the second quote. 问题在于,文件中写入的内容可能是Hello\\n ,如果您读了整行,则打印"Hello\\n" ,这会使换行符位于第二个引号的前面。 Use the strip() method to get rid of any trailing whitespaces like so: 使用strip()方法来消除任何尾随空格,如下所示:

 for line in open('greeting.txt', "r"): print ('"%s"' % line.strip())

However I would suggest changing your code to: 但是我建议将您的代码更改为:

with open('greeting.txt', "r") as f:
    for line in f: print ('"%s"' % line.strip())

Since I personally do not like to have open without making sure, that the file is being closed as soon as I am done with it. 由于我个人不喜欢在不确定的情况下open文件,因此我一完成文件就立即将其关闭。

There is a end of line character in your text file after Hello. Hello之后,文本文件中有一个行尾字符。 That end of line is also getting enclosed in the double quotes and causing the second quote to get printed on the second line. 该行的末尾也被括在双引号中,并导致第二个引号被打印在第二行上。 You should strip the end of line using rstrip() 您应该使用rstrip()删除行尾

for line in open('greeting.txt', "r"): print ('"%s"' % line.rstrip())

您可以使用rstrip()函数rstrip()尾随的空格。

for line in open('greeting.txt', "r"): print ('"%s"' % line.rstrip())

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

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