how to add options to inflect number-to-word?

Question:

I have a program which calculates the number of minutes of a person’s age. It works correctly. However, I want to ask if I can print the first letter capitalized.

from datetime import datetime, date
import sys
import inflect
inflector = inflect.engine()

def main():
    # heute = date.today()
    user = input('Date of birth: ')
    min_preter(user)


def min_preter(data):
     try:
        data != datetime.strptime(data, '%Y-%m-%d')

        # Get the y-m-d in current time
        today = date.today()

        # die y-m-d teilen
        year, month , day = data.split('-')
        # Convert to datetime
        data = date(year=int(year), month=int(month), day=int(day))

        # And valla
        end = (today - data).total_seconds() / 60

        # Convert to words
        words = inflector.number_to_words(end).replace('point zero','minutes').upper()
        return words
    except:
        sys.exit('Invalid date')
        # convert from string format to datetime format

if __name__ == "__main__":
    main()

Here is the output when I enter e.g 1999-01-01:

twelve million, four hundred and fifty-seven thousand, four hundred and forty point zero

where I expected

Twelve million, four hundred and fifty-seven thousand, four hundred and forty minutes

first word ‘Twelve'(first letter capitalize)

I don’t know what this point zero is. I just want the minutes at the end.

Thank you

Asked By: Payam

||

Answers:

Just replace .upper() by capitalize() in your code

An alternative to your replace would be to obtain the total number of minutes as an integer (point zero is because end is a float number) :

end = int((today - data).total_seconds() / 60)

In that case, your words variable would be :

words = inflector.number_to_words(end).capitalize() + " minutes"
Answered By: L4ur3nt

You can use string.capitalize(). So you can do that:

return words.capitalize()

… and as for the "point zero", try converting the result to int before running your function, like

end = int((today - data).total_seconds() / 60)
Answered By: Marcos Silva

You can use .capitalize() to capitalize the first word of the string.

EXAMPLE: words.capitalize()

"twelve million, four hundred and fifty-seven thousand, four hundred and forty point zero".capitalize()

OUTPUT

'Twelve million, four hundred and fifty-seven thousand, four hundred and forty point zero'

Regarding point zero

  • This particular code end = (today - data).total_seconds() / 60 is giving output as float which is leading to point zero so instead of division use floor division i.e. // instead of / which will return integer and hence point zero will be gone or else convert end to int.
  • Lastly add minutes string i.e. end + ' minutes' to final result.
Answered By: GodWin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.