Home > Back-end >  How can my function print out lines of "#". The argument is a list of integers and they sp
How can my function print out lines of "#". The argument is a list of integers and they sp

Time:11-21

My function at the moment looks like this:

def list_of_char(my_list: list):
    n = "#"
    my_new_list = [i*n for i in my_list]
    return my_new_list

if __name__ == "__main__":
    print(list_of_char([2,3]))

It prints out:

['##', '###'] 

but my output must be like this:

##
###

CodePudding user response:

Your list_of_char() func returns a list, which you then print out. So you're seeing exactly what you're asking for.

If you want to print out strings, you need to either create the string in list_of_char() and return the string instead of a list. Or, you can take the returned list and print the elements of that list one at a time. Or you can convert the list of strings into a single string and print that out.

In the func you could change:

return my_new_list

to:

return '\n'.join(my_new_list)

which then would have the func return a single string.

In the alternative, you could change "main" from:

print(list_of_char([2,3]))

to:

print('\n'.join(list_of_char([2,3])))

Or, you could handle the list items one at a time (which now means not adding the extra newline (because you'll get one by default from print():

for line in list_of_char([2,3]):
    print(line)
  • Related