NeedHelp
NeedHelp

Reputation: 63

List \n with f-String format

I know you can't use \n in f string formats{} but I'm trying to figure out how to print a list separated by line.

Each printed number should have a width of 10

# Output
#         12
#         28
#         45
#         47
#         52
#         71
#         95
#        122
#        164

I'm not allowed to use any external modules such as itertools or functools to answer this question.

I've tried

num_list = [12, 16, 17, 2, 5, 19, 24, 27, 42]
new_list = num_list.copy()
for n in range(1, len(new_list)):
    new_list[n] += new_list[n-1]

print(f'{*new_list:10f, sep = "\n"}')

Upvotes: 3

Views: 256

Answers (4)

Errol
Errol

Reputation: 610

Try this, it will print a line every loop and using .rjust() to add 10 leading spaces.

for n in range(1, len(new_list)):
    new_list[n] += new_list[n-1]

for num in new_list:
    print(f"{num}".rjust(10))

Upvotes: 2

kederrac
kederrac

Reputation: 17322

you could use str.join:

print('\n'.join(f'{n}'.rjust(10) for n in  new_list))

or use the built-in function print with an unpacked generator expression and the separator set as \n:

print(*(f'{n}'.rjust(10) for n in  new_list), sep='\n')

output:

    12
    28
    45
    47
    52
    71
    95
   122
   164

Upvotes: 0

spackle0
spackle0

Reputation: 91

If you want to stick with the f-string as you were intending, just print it as you go along with the calculation. This also avoids an additional iteration over the list.

num_list = [12, 16, 17, 2, 5, 19, 24, 27, 42]
new_list = num_list.copy()

print(f'{new_list[0]:10}') # This gets you the first value

for n in range(1, len(new_list)):
    new_list[n] += new_list[n-1]
    print(f'{new_list[n]:10}') # This prints as you go

Upvotes: 1

NeedHelp
NeedHelp

Reputation: 63

Thank you @chepner!! This worked

print('\n'.join([f'{x:10}' for x in new_list]))

Upvotes: 2

Related Questions