Skip to content
Advertisement

Change substring in a string to an corresponding item in a dictionary using Python

I get a string like “29 jan. 2021”. I want to convert the swedish substring “jan.” to the corresponding english month name, in this case “Jan” so the result would be “29 Jan 2021”. Then I can use this string to convert it into a date object.

I have a dictionary that has a key:value with the swedish key name and corresponding english month name as value:

monthNameDictionary = {
    "jan.": "Jan",
    "feb.": "Feb",
    "mars": "Mar",
    "apr.": "Apr",
    "maj": "May",
    "juni": "Jun",
    "juli": "Jul",
    "aug.": "Aug",
    "sep.": "Sep",
    "okt.": "Oct",
    "nov.": "Nov",
    "dec.": "Dec",
}

How can I use this or some other way to convert the string into a string with the english month name?

Advertisement

Answer

Just for completeness: If you really want to replace the strings, use this (assumes that every string to be replaced is present at most once):

monthDict = {
    "jan.": "Jan",
    "feb.": "Feb",
    "mars": "Mar",
    "apr.": "Apr",
    "maj": "May",
    "juni": "Jun",
    "juli": "Jul",
    "aug.": "Aug",
    "sep.": "Sep",
    "okt.": "Oct",
    "nov.": "Nov",
    "dec.": "Dec",
}
inStr = "29 jan. 2021"
for month in monthDict: # iterating directly over a dict iterates over it's keys
    inStr = inStr.replace(month, monthDict[month])
print(inStr)

EDIT: If you have multiple occurrences of the same word, use inStr = re.sub(month, monthDict, inStr) instead.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement