Skip to content
Advertisement

How to remove unnecessary “and” in inflect num to words python package

I’m using the python package inflect to convert numbers to words. I would like to know how I can have inflect convert the numbers the right way without unnecessary “and” in the end result.

Here’s my code

from datetime import date
import inflect, sys
def main():
    print(time_check(input("What's your DOB?: ")))

def time_check(check):
    p = inflect.engine()
    year, month, day = check.split("-")
    year, month, day = int(year), int(month), int(day)
    dob = date(year, month, day)
    diff = date.today() - dob

    # Convert days to minutes & then use inflect to convert the number to words
    ans = p.number_to_words(diff.days*24*60)
    return f"{ans.capitalize()} minutes"

if __name__ == "__main__":
    main()

When I input "2021-10-10" as my Date of Birth(DOB), ans will become

ans = p.number_to_words(525,600)

This will then print “Five hundred and twenty five-thousand, six hundred minutes” but I don’t want that as that is partially incorrect. I want my code to print “Five hundred twenty five-thousand, six hundred minutes” without the “and”.

I know I can use the replace method to replace the “and” with an empty string, but I don’t want to do that. I want the inflect python package to convert numbers to words using this right way.

I hope you guys can understand the problem here & hope to get your help.

Advertisement

Answer

Just set andword in number_to_words() as it is ‘and’ by default. See the inflect documentation for more details.

p.number_to_words(diff.days*24*60, andword = '')

This will print the following directly (for 2021-10-10):

Five hundred twenty-five thousand, six hundred minutes
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement