python - 在一行循环中获取结果
问题描述
我的输出:
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}')
解决方案
如果你想要的只是一个字符串,我不太确定为什么你在那里有一个计数器,但这将完成这项工作。
用户.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
推荐阅读
- javascript - 如何将一组数组(字符串格式)推送到数组中?
- oracle - 流水线函数在编译时给出“PLS-00630”错误
- python - 将 2 .CSV 与未知数量的列和名称进行比较
- r - 在时间序列中创建平稳性的问题
- lda - 如何获得两个模型的主题连贯性分数,然后将其用于比较?
- mysql - 如果 MySQL 数据库中不存在另一个对象,如何创建 SQL 查询来保存对象?
- nuxt.js - 在根路由 NuxtJS 中使用 get param
- php - 如何在php中添加.docx的下载链接
- ios - 本地化自然格式的 API 数据列表
- c++ - 使用选项 -fstack-usage 和 -fdump-rtl-expand 匹配 g++ 生成的文件中的标识符