如何格式化列表以在 python 脚本中将每个元素打印在单独的行上?

问题描述 投票:0回答:1
# open the sample file used

file = open('logFile.txt')

# read the content of the file opened

content = file.readlines()

print(content[287:330])


#need to print separate line for 287 line to 330.

我期待单独的线路。 请帮助我。

python python-3.x
1个回答
1
投票

这里有几种不同的方法,都可以利用此代码片段来读取文件的内容:

with open('logFile.txt') as file:
    content = file.readlines()
1.使用循环和
end
 函数的 
print
参数:
for line in content[287:330]:
    print(line, end='')
2.使用
str.join
print('\n'.join(content[287:330]))
3.使用参数解包 (
*
) 和
sep
 函数的 
print
参数:
print(*content[287:330], sep='\n')
© www.soinside.com 2019 - 2024. All rights reserved.