Search code examples
pythonstringlistformataccumulator

Using a loop + string accumulator to format a List


I created a function definition to get user input (numbers) and then store it into a list.

[52.0, 55.0, 567.0, 92.0, 2.0, 5.0]

and I'm trying to format using a loop w/ string accumulator so it'll look something like this:

{$52.00, $55.00, $567.00, $92.00, $2.00, $5.00}

all without using the .join method. I can easily do it with the .join method, but the goal is to make it in a function definition as a loop so I can use it else where in my program.


Solution

  • Whats the motiviation in not using join?

    lst = [52.0, 55.0, 567.0, 92.0, 2.0, 5.0]
    
    def foo(lst):
        bar = ''
        for i in lst:
            i = format(i, '.2f')
            bar+= '${}, '.format(str(i))
        bar = bar.rstrip(', ')
        return '{'+bar+'}'
    
    print(foo(lst))