Format string and fill with elements of array

Viewed 468

I've got a string which I want to format() with elements of an array (incrementally). Right now, the elements are placed via .format(*arr) but I want to run formatNumbers() for each element first and have its output placed in the string.

def formatNumbers(number):
    return str("{:,}".format(number)).replace(",", " ")

def displayNumbers():
    arr = [ 1000, 2000, 3000, 4000, 5000 ]
    myString = "Numbers:\n{}\n{}\n{}\n{}\n{}".format(*arr)
    print(myString)

Is there a fast way of doing this? Just writing .format(formatNumbers(*arr)) doesn't seem to work. Do I need to make a "temporary array" to store the strings an then use the * operator to iterate through them, or is there an easier way?

Current output:

Numbers: 
1000 
2000 
3000 
4000 
5000

Desired output (via calling formatNumbers()):

Numbers: 
1 000
2 000 
3 000 
4 000 
5 000
3 Answers

You can use a list comprehension.

myString = "Numbers:"+("\n{}" * len(arr)).format(*[formatNumbers(x) for x in arr])
# or
myString = "Numbers:" + "".join(["\n{}".format(formatNumbers(x)) for x in arr])

You can use the built-in map function to apply another function to every element of a list. In your case, it would look like this:

myString = "Numbers:\n{}\n{}\n{}\n{}\n{}".format(*map(formatNumbers, arr))

You can use map() to apply function formatNumbers() to all elements of arr:

myString = "Numbers:\n{}\n{}\n{}\n{}\n{}".format(*map(formatNumbers, arr))

And the output will be:

Numbers:
1 000
2 000
3 000
4 000
5 000

Additionally you can replace the multiple \n in your formatted string and use join() instead:

import os


arr = [ 1000, 2000, 3000, 4000, 5000 ]
print(f"Numbers: \n{os.linesep.join(map(formatNumbers, arr))}")
Related