简体   繁体   English

如何删除不需要的空白

[英]How to remove unwanted white space

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披萨 $10

  2. burger $ 7汉堡 $7

  3. hotdog $ 4热狗 $4

  4. salad $ 8沙拉 $8

I dont want a white space between the $ and the value, how would I do this我不想要 $ 和值之间的空白,我该怎么做

You could use an f-string.您可以使用 f 字符串。

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的分隔符指定为空字符串,然后在必要时手动添加空格。

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.现在如果你想用数字打印这些,你可以使用 enumerate 和 for 循环。

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

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) (从技术上讲,在这种情况下不需要字符串转换 - 因为您的menu_price数组已经包含字符串)

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))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM