Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.removeprefix() method on a string does nothing

Upon entering an input, say $50.00, I get an error that says ValueError: could not convert string to float: '$50.00'. I already have dollars.removeprefix("$") in line 10, the .removeprefix() method simply does nothing. What am I doing wrong? Full code below:

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are not reassigning your result to a variable.

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)

You should really improve your code to perform some more input validation. What happens to your script if I do this?

>>> How much was the meal? 
>>> 50$

A simple idea to make it more robust:

import re

def dollars_to_float(dollars):
    # Extract numbers, ignore all else
    dollars = re.sub(r"[^1-9\.]", "", dollars)
    return float(dollars)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading