简体   繁体   English

如何在没有奇怪间距的情况下打印列表中的每个项目?

[英]How to print a each item in list without weird spacing?

I have a list gathered from a text file, f , named fList .我有一个从名为fList的文本文件f收集的列表。 I want to print each item in list separately on a new line and I used the following.我想在新行上分别打印列表中的每个项目,我使用了以下内容。

f.seek(0)
fList = f.readlines()
items = fList[::2] #Every other value
    
print("\n Catalogue Items: \n")
print(*items)

When printing in the console, the first item always has a weird spacing.在控制台中打印时,第一项总是有一个奇怪的间距。 Image of output in console output 在控制台中的图像这里。
The first item always does not follow the spacing of the rest when printed.打印时第一项始终不遵循 rest 的间距。

Your text appears to include carriage return characters.您的文本似乎包含回车符。

Printing *items only adds the spaces between elements, not the carriage returns, or a space before the first item.打印*items只会在元素之间添加空格,而不是回车符或第一项之前的空格。

Assuming you want those carriage returns, just add a space to the print statement (to add a space before the first element too), or use join to avoid adding the spaces between elements.假设您想要这些回车符,只需在 print 语句中添加一个空格(在第一个元素之前也添加一个空格),或者使用join来避免在元素之间添加空格。

print(''.join(items)) # no spaces

Or...或者...

print('', *items) # consistent single spaces

Or...或者...

print(' ', '  '.join(items)) # consist double spaces

Try using the var.strip() function, it gets rid of spaces on both sides尝试使用 var.strip() function,它去掉了两边的空格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM