Converting Roman Numerals to integers in python

No need to reinvent the wheel (unless you want to). Python once came with a converter (so you can go to the Python 3.4.1 source code and grab the module at this location: /Python-3.4.1/Doc/tools/roman.py; or perhaps install it with pip as someone in the comments said here; I haven’t verified the pip version; anyway, then you can do):

import roman;
n=roman.fromRoman("X"); #n becomes 10

If you need it for numbers 5000 and above, you’ll need to write a new function, though, and maybe make your own font to represent the lines over the roman numerals. (It will only work with some numbers, at that. Stopping at 4999 is a really good idea.)

To convert to roman numerals, use roman.toRoman(myInt).

Alternatively (for converting to Roman numerals only), you can do this in Python 3.9.2 (which I only partially understand due to a lack of documentation; so, all my arguments probably aren’t right; but, it seems to work; formatter is depreciated anyway; so, don’t expect it to stay around a long time):

import formatter
a=formatter.AbstractFormatter("I don't know what I'm supposed to put here, but it doesn't seem to matter for our purposes.")
roman_numeral=a.format_roman(case="I", counter=5) #Case doesn't seem to matter, either.
#roman_numeral now equals "V"

Someone else actually linked to the same source code the roman module uses in one of the comments above, but I don’t believe they mentioned that it actually comes with Python. It doesn’t seem to come with Python anymore, but it did in version 3.4.1.

Leave a Comment