Home > Blockchain >  How to remove unwanted white space
How to remove unwanted white space

Time:10-23

Using python

In my code:

print('Menu')
menu_items = ['pizza','burger','hotdog','salad']
menu_price = ['10','7','4','8']

print('0)',menu_items[0], '$', menu_price[0])

print('1)',menu_items[1], '$', menu_price[1])

print('2)',menu_items[2], '$', menu_price[2])

print('3)',menu_items[3], '$', menu_price[3])

I get: Menu

  1. pizza $ 10

  2. burger $ 7

  3. hotdog $ 4

  4. salad $ 8

I dont want a white space between the $ and the value, how would I do this

CodePudding user response:

You could use an f-string.

print(f"0) {menu_items[0]} ${menu_price[0]}")

And with a format specifier to ensure the price is printed correctly.

print(f"0) {menu_items[0]} ${menu_price[0]:.2f}")

Alternatively, you can specify the separator to print as being an empty string, and then manually add spaces where necessary.

print('0) ', menu_items[0], ' $', menu_price[0], sep='')

One more thing

Structuring your data as multiple arrays works, but it's a bad design. You'd be better off keeping your related data stored together.

Rather than:

menu_items = ['pizza', 'burger', 'hotdog', 'salad']
menu_price = ['10', '7', '4', '8']

Store this as a list of tuples storing the description and price of each item.

menu_items = [('pizza', 10), ('burger', 7), ('hotdog', 4), ('salad', 8)]

Now if you want to print these with numbers, you can use enumerate and a for-loop.

for index, (description, price) in enumerate(menu_items):
    print(f"{index:-2d}) {description:20s} ${price:4.2f}")

And the result is:

 0) pizza                $10.00
 1) burger               $7.00
 2) hotdog               $4.00
 3) salad                $8.00

CodePudding user response:

Try this :)

print('0)', menu_items[0], '$'   str(menu_price[0]))

(Technically, the string conversion is not necessary in this case - since your menu_price array already contains strings)

CodePudding user response:

You can use this:

print('Menu')
menu_items = ['pizza', 'burger', 'hotdog', 'salad']
menu_price = ['10', '7', '4', '8']
[print(f"{i}) {menu[0]} ${menu[1]}") for i, menu in enumerate(zip(menu_items, menu_price))]
  • Related