如何使用 python 删除函数中的 space
How to remove space in function with python
这可能很简单,但我只做了一个星期。
我正在学习定义函数,所以我参加了俄亥俄州哥伦布市的税务考试。
无论我尝试什么,我总是在美元金额和总数之间得到 space。我希望有人有解决方案。我又是新手,刚来这里学习。
>>> def tax_ohio(subtotal):
'''(number) -> number
Gives the total after Ohio tax given the
cost of an item.
>>> tax_ohio(100)
7.5
>>> tax_ohio(50)
.75
'''
total = round(subtotal*1.075, 2)
return print('$',total)
>>> tax_ohio(100)
$ 107.5
在打印函数中使用 +
而不是逗号。,
在打印函数中将打印默认的 sep
值,即 space.
print('$'+str(total))
使用字符串格式:
print('${}'.format(total))
为了避免 space,使用 +
运算符连接变量:
def tax_ohio(subtotal):
total = round(subtotal*1.075, 2)
print '$'+str(total)
,
会自动在变量之间附加一个 space。
PS。请注意,您必须手动将浮点数转换为字符串,否则您会收到以下错误:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
因为您使用的是带多个参数的 print,它会自动在中间添加空格。而是使用字符串连接。请改用 $+str(total)
。
str()
函数将数字转换为字符串
和 +
运算符连接(连接)两个给定的字符串。
这可能很简单,但我只做了一个星期。
我正在学习定义函数,所以我参加了俄亥俄州哥伦布市的税务考试。
无论我尝试什么,我总是在美元金额和总数之间得到 space。我希望有人有解决方案。我又是新手,刚来这里学习。
>>> def tax_ohio(subtotal):
'''(number) -> number
Gives the total after Ohio tax given the
cost of an item.
>>> tax_ohio(100)
7.5
>>> tax_ohio(50)
.75
'''
total = round(subtotal*1.075, 2)
return print('$',total)
>>> tax_ohio(100)
$ 107.5
在打印函数中使用 +
而不是逗号。,
在打印函数中将打印默认的 sep
值,即 space.
print('$'+str(total))
使用字符串格式:
print('${}'.format(total))
为了避免 space,使用 +
运算符连接变量:
def tax_ohio(subtotal):
total = round(subtotal*1.075, 2)
print '$'+str(total)
,
会自动在变量之间附加一个 space。
PS。请注意,您必须手动将浮点数转换为字符串,否则您会收到以下错误:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
因为您使用的是带多个参数的 print,它会自动在中间添加空格。而是使用字符串连接。请改用 $+str(total)
。
str()
函数将数字转换为字符串
和 +
运算符连接(连接)两个给定的字符串。