Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}')
like image 871
NeedHelp Avatar asked Feb 22 '26 01:02

NeedHelp


2 Answers

Thank you @chepner!! This worked

print('\n'.join([f'{x:10}' for x in new_list]))
like image 127
NeedHelp Avatar answered Feb 24 '26 15:02

NeedHelp


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))
like image 21
Errol Avatar answered Feb 24 '26 14:02

Errol