如何用python删除函数中的空格

2024-04-26 23:33:47 发布

您现在位置:Python中文网/ 问答频道 /正文

可能很简单,但我只做了一个星期。你知道吗

我正在学习定义函数,所以我在俄亥俄州哥伦布市做税务测试。你知道吗

不管我怎么做,我总是在美元金额和总额之间找到一个空格。我希望有人能找到解决办法。我又是一个新手,只是来学习的。你知道吗

>>> def tax_ohio(subtotal):
        '''(number) -> number

Gives the total after Ohio tax given the
cost of an item.

>>> tax_ohio(100)
$107.5
>>> tax_ohio(50)
$53.75
'''
total = round(subtotal*1.075, 2)
return print('$',total)

>>> tax_ohio(100)
$ 107.5

Tags: the函数number定义def金额totaltax
3条回答

使用字符串格式:

print('${}'.format(total))

在print函数中使用+而不是逗号。print函数中的,将打印默认的sep值,即空格。你知道吗

print('$'+str(total))

为避免空格,请使用+运算符连接变量:

def tax_ohio(subtotal):
   total = round(subtotal*1.075, 2)
   print '$'+str(total)

,会自动在变量之间追加一个空格。你知道吗

请注意,您必须手动将浮点转换为字符串,否则将收到以下错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

相关问题 更多 >