【问题标题】:Get result in one line loop在一行循环中获取结果
【发布时间】:2021-09-25 13:50:53
【问题描述】:

我的输出:

I have CMShehbaz
CMShehbaz

预期:

I have CMShehbaz CMShehbaz

我正在尝试在一行中获取结果。我试过end="",concat +,但没有 工作。我想要一行结果。

lines = []
with open('user.txt') as f:
    lines = f.readlines()

count = 0
for line in lines:
    count += 1
    print("I have {}  {}".format(line,line) )
    print(f'line {count}: {line}')

【问题讨论】:

  • 在打印之前,请尝试line = line.strip()。它会删除末尾的空格。
  • readlines() 也读取换行符,返回数组为 [["CMShehbaz\n"],需要使用 line.strip()。
  • 请在您的问题中添加一小部分user.txt 中的内容。
  • @usman 我更新的答案对您有帮助吗?如果是这样,最好将其标记为答案

标签: python string loops format


【解决方案1】:

如果你想要的只是一个字符串,我不太确定为什么你有一个计数器,但这将完成这项工作。

user.txt

CMShehbaz1
CMShehbaz2
CMShehbaz3

python 文件

with open('user.txt') as f:
    foo = "I have "
    bar = " ".join(line.strip() for line in f)
    print(foo+bar)

# Or you can do

    foo = " ".join(line.strip() for line in f)
    print(f"I have {foo}")

给你输出:

I have CMShehbaz1 CMShehbaz2 CMShehbaz3

如果你想知道 foo 中有多少个名字,那么你可以这样做

    print(len(foo.split(' ')))  # this will give you 3

【讨论】:

    【解决方案2】:

    我怀疑“user.txt”是一个用户名列表,每个用户名都换行。

    所以在你的代码中 line 看起来像 "USER\n"

    您可以去掉“\n”字符使用之前发布的一些解决方案:How to read a file without newlines?

    【讨论】:

      猜你喜欢
      • 2017-02-02
      • 2014-06-20
      • 1970-01-01
      • 2019-04-21
      • 2015-09-18
      • 2014-10-02
      • 2017-05-17
      • 2017-02-07
      • 2013-04-20
      相关资源
      最近更新 更多