0

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?

Python learner
  • 1,159
  • 1
  • 8
  • 20
  • 1
    Does this answer your question? [Ordinal numbers replacement](https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement) – TheMaster Oct 18 '21 at 09:40

1 Answers1

2

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'
user2390182
  • 72,016
  • 6
  • 67
  • 89