Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert number to Cardinal in python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading