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:

JavaScript

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):

JavaScript

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