Home > Software design >  How to print a each item in list without weird spacing?
How to print a each item in list without weird spacing?

Time:01-25

I have a list gathered from a text file, f, named fList. 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 here.
The first item always does not follow the spacing of the rest when printed.

CodePudding user response:

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.

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(items)) # no spaces

Or...

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

Or...

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

CodePudding user response:

Try using the var.strip() function, it gets rid of spaces on both sides

  • Related