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
x
15
15
1
monthNameDictionary = {
2
"jan.": "Jan",
3
"feb.": "Feb",
4
"mars": "Mar",
5
"apr.": "Apr",
6
"maj": "May",
7
"juni": "Jun",
8
"juli": "Jul",
9
"aug.": "Aug",
10
"sep.": "Sep",
11
"okt.": "Oct",
12
"nov.": "Nov",
13
"dec.": "Dec",
14
}
15
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
1
19
19
1
monthDict = {
2
"jan.": "Jan",
3
"feb.": "Feb",
4
"mars": "Mar",
5
"apr.": "Apr",
6
"maj": "May",
7
"juni": "Jun",
8
"juli": "Jul",
9
"aug.": "Aug",
10
"sep.": "Sep",
11
"okt.": "Oct",
12
"nov.": "Nov",
13
"dec.": "Dec",
14
}
15
inStr = "29 jan. 2021"
16
for month in monthDict: # iterating directly over a dict iterates over it's keys
17
inStr = inStr.replace(month, monthDict[month])
18
print(inStr)
19
EDIT: If you have multiple occurrences of the same word, use inStr = re.sub(month, monthDict, inStr)
instead.