【问题标题】:How to get rid of the last whitespace when printing with end=" "?使用 end=\" \" 打印时如何去掉最后一个空格?
【发布时间】:2022-12-20 01:31:25
【问题描述】:

任务: 创建一个解决方案,它接受标识文本文件名称的输入,例如“WordTextFile1.txt”。每个文本文件包含三行,每行一个词。使用 open() 函数和 write() 和 read() 方法,与输入文本文件交互,将由三个现有单词组成的新句子字符串写入新行的文件内容末尾。输出新的文件内容。

解决方案输出应采用以下格式 猫 追逐 狗 猫追狗

“WordTextFile1.txt”在不同的行中每个只有 3 个单词 猫 追逐 狗

这就是我所拥有的,但是句子的最后一行有一个额外的空格,这破坏了我的程序。我该怎么做才能摆脱空白并修复我的代码?帮助!

file = input()
with open(file, "r+") as f:
    list_words = f.readlines()

for word in list_words:
    print(word.strip())
for word in list_words:
    print(word.strip(), end = " ")    

this is current output:
student
reads
book
student reads book(extra whitespace)

【问题讨论】:

  • 先加入,再打印。

标签: python list file


【解决方案1】:

您通过 word.strip() 正确删除了最后一个空格,但添加 end = " " 只是再次添加了最后一个空格。将其更改为:

file = input()
with open(file, "r+") as f:
    list_words = f.readlines()

for word in list_words:
    print(word.strip())
print(' '.join([word.strip() for word in list_words]) # this should work

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 2011-03-06
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多