Home > Software design >  is there any easier way to put word after numbers in string?
is there any easier way to put word after numbers in string?

Time:10-19

Hi I want to give text to code and code change every Cardinal numbers to Ordinal numbers in python

Input : str = 'I was born in September 22 and I am 1 in swimming'

and change it to : I was born in September 22th and I am 1st in swimming

How can I do that in easiest way?

CodePudding user response:

Write a function to make ordinals, e.g. this one taken from this excellent answer:

def make_ordinal(match):
    n = match.group(0)
    n = int(n)
    suffix = ['th', 'st', 'nd', 'rd', 'th'][min(n % 10, 4)]
    if 11 <= (n % 100) <= 13:
        suffix = 'th'
    return str(n)   suffix

and use regular expressions to do the replacement, using re.sub:

import re

s = "I was born in September 22 and I am 1 in swimming"

re.sub(r"\d ", make_ordinal, s)
# 'I was born in September 22nd and I am 1st in swimming'
  • Related