I want replace any number in String to Cardinal num then print it
I have one challenge: The user may not draw any spaces between the number and the next character
input:
1, we have to pay attention to 12 points!22
output:
1st, we have to pay attention to 12th points!22nd
>Solution :
You may do this:
import re
s = '1, we have to pay attention to 12 points!22'
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4])
out = re.sub(r'\d+', lambda x: ordinal(int(x[0])),s)
print(out)
# 1st, we have to pay attention to 12th points!22nd