字符串上的 .removeprefix() 方法什么都不做
.removeprefix() method on a string does nothing
输入输入后,比如 50.00 美元,我收到一条错误消息 ValueError: could not convert string to float: '.00'
。我在第 10 行已经有了 dollars.removeprefix("$")
,.removeprefix() 方法什么都不做。我究竟做错了什么?完整代码如下:
def main():
dollars = dollars_to_float(input("How much was the meal? "))
percent = percent_to_float(input("What percentage would you like to tip? "))
percent = percent / 100
tip = dollars * percent
print(f"Leave ${tip:.2f}")
def dollars_to_float(dollars):
dollars.removeprefix("$")
return float(dollars)
def percent_to_float(percent):
percent.removesuffix("%")
return float(percent)
main()
您没有将结果重新分配给变量。
def main():
dollars = dollars_to_float(input("How much was the meal? "))
percent = percent_to_float(input("What percentage would you like to tip? "))
percent = percent / 100
tip = dollars * percent
print(f"Leave ${tip:.2f}")
def dollars_to_float(dollars):
dollars = dollars.removeprefix("$")
return float(dollars)
def percent_to_float(percent):
percent = percent.removesuffix("%")
return float(percent)
您真的应该改进您的代码以执行更多的输入验证。如果我这样做,您的脚本会怎样?
>>> How much was the meal?
>>> 50$
一个让它更健壮的简单想法:
import re
def dollars_to_float(dollars):
# Extract numbers, ignore all else
dollars = re.sub(r"[^1-9\.]", "", dollars)
return float(dollars)
输入输入后,比如 50.00 美元,我收到一条错误消息 ValueError: could not convert string to float: '.00'
。我在第 10 行已经有了 dollars.removeprefix("$")
,.removeprefix() 方法什么都不做。我究竟做错了什么?完整代码如下:
def main():
dollars = dollars_to_float(input("How much was the meal? "))
percent = percent_to_float(input("What percentage would you like to tip? "))
percent = percent / 100
tip = dollars * percent
print(f"Leave ${tip:.2f}")
def dollars_to_float(dollars):
dollars.removeprefix("$")
return float(dollars)
def percent_to_float(percent):
percent.removesuffix("%")
return float(percent)
main()
您没有将结果重新分配给变量。
def main():
dollars = dollars_to_float(input("How much was the meal? "))
percent = percent_to_float(input("What percentage would you like to tip? "))
percent = percent / 100
tip = dollars * percent
print(f"Leave ${tip:.2f}")
def dollars_to_float(dollars):
dollars = dollars.removeprefix("$")
return float(dollars)
def percent_to_float(percent):
percent = percent.removesuffix("%")
return float(percent)
您真的应该改进您的代码以执行更多的输入验证。如果我这样做,您的脚本会怎样?
>>> How much was the meal?
>>> 50$
一个让它更健壮的简单想法:
import re
def dollars_to_float(dollars):
# Extract numbers, ignore all else
dollars = re.sub(r"[^1-9\.]", "", dollars)
return float(dollars)