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.


Roman numerals are read from left to right, as you add or subtract the value of each symbol.

If a value is lower than the following value, it will be subtracted. Otherwise it will be added.

For example, we want to conver the Roman numeral MCMLIV to an Arabic number:

M = 1000 must be added, because the following letter C =100 is lower.
C = 100 must be subtracted because the following letter M =1000 is greater.
M = 1000 must be added, because the following letter L = 50 is lower.
L = 50 must be added, because the following letter I =1 is lower.
I = 1 must be subtracted, because the following letter V = 5 is greater.
V = 5 must be added, because there are no more symbols left.

We can now calculate the number:

1000 - 100 + 1000 + 50 - 1 + 5 = 1954 

ref : http://www.mathinary.com/roman_numerals_from_roman_numerals_to_arabic_numbers.jsp

def from_roman(num):
    roman_numerals = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
    result = 0
    for i,c in enumerate(num):
        if (i+1) == len(num) or roman_numerals[c] >= roman_numerals[num[i+1]]:
            result += roman_numerals[c]
        else:
            result -= roman_numerals[c]
    return result