499602D2
499602D2

Reputation: 45

Multi-line string indentation with .format()

I'm supposed to create a receipt in string format, which will then be passed back to the main program, which then prints it.

So, I have two strings which contain the prices with \n in between each one:

food_prices = "\n22.40\n13.40\n"
drink_prices = "\n11.50\n6.90\n"

They were created from lists with float values - I tried to do this with for-loops, but I never got it to work; all I got were incredibly buggy prints after the receipt string was passed on to the main program.

I'm trying to get them formatted with .format() so that each is printed on a line of its own (due to the \n), indented to the right with 16 spaces of "room". Example of what the output is supposed to be:

1234567890123456 # For readability, ignore
Food:
           22.40
           13.40
Drinks:
           11.50
            6.90
------------------------------
Total      54.20

What I have tried:

 receipt = (...
        "Food:\n"
        "{:>16}"
        "Drinks:\n"
        "{:>16}"
        "------------------------------\n"
        "{:>7.2f}"
        "Total {:>7.2f}\n").format(food_prices, drink_prices, total)

What the output looks like:

Food:
 12.4
5.43
7.65
Drinks:
   5.4
8.76
5.4
------------------------------
Total      45.04 

The indentation does work with only a single price in the string ("\n0.00\n"), though. I'm not exactly sure how this should/could be done. I've referenced the official documentation (and PEP) and done some Googling.

Upvotes: 0

Views: 1568

Answers (1)

michael_heath
michael_heath

Reputation: 5372

I will use your list rather then your string as the string is not of a convenient format.

2 options to do this task. First uses for loops to build the string in parts. The second uses len() to help create the full pattern.

food_prices = [22.40, 13.40]
drink_prices = [11.50, 6.90]

total = sum(food_prices + drink_prices)


# Option 1 (in parts)

summary = 'Food:\n'

for item in food_prices:
    summary += '{:>16.2f}\n'.format(item)

summary += 'Drinks:\n'

for item in drink_prices:
    summary += '{:>16.2f}\n'.format(item)

summary += '-' * 30 + '\nTotal {:>10.2f}\n'.format(total)

print(summary)


# Option 2 (all at once)

summary = ('Food:\n' + '{:>16.2f}\n' * len(food_prices) +
    'Drinks:\n' + '{:>16.2f}\n' * len(drink_prices) +
    '-' * 30 + '\nTotal {:>10.2f}\n'
    ).format(*food_prices, *drink_prices, total)

print(summary)

Note: Using '-' * 30 saves you manually typing - 30 times.

Upvotes: 2

Related Questions