is there any easier way to put word after numbers in string?

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 I want to change it to :

I was born in September 22th and I am 1st in swimming

How can I do that in easiest way?

Upvotes: 0

Views: 87

Answers (1)

user2390182
user2390182

Reputation: 73460

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'

Upvotes: 2

Related Questions