【问题标题】:Trying to print multiple variable under loop尝试在循环下打印多个变量
【发布时间】:2019-10-14 09:27:26
【问题描述】:

这是我尝试过的

f = open('names.txt')
for people in f:
    print('{0} and {1}'.format(people, people))

输出:

john
and john

vlad 
and vlad

但我的预期输出是

john and john
vlad and vlad

这里出了什么问题以及如何解决?

【问题讨论】:

  • 什么是 f?我认为人们可能在主题结束时有一个换行符
  • 大概 f 中的每个项目都以换行符结尾 - 也许它是一个文件?
  • @jonrsharpe 是的。

标签: python python-3.x loops for-loop


【解决方案1】:

这个怎么样:

people = people.rstrip()
print('{0} and {1}'.format(people, people))

【讨论】:

    【解决方案2】:

    您可以尝试删除换行符:

    f = open('names.txt')
    for people in f:
        people = people.replace("\n", "")
        print('{0} and {1}'.format(people, people))
    

    这样,文件 f 中的下一个人应该只有一个新行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多