首页 > 解决方案 > 在一行循环中获取结果

问题描述

我的输出:

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}')

标签: pythonstringloopsformat

解决方案


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

用户.txt

CMShehbaz1
CMShehbaz2
CMShehbaz3

蟒蛇文件

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

推荐阅读