I have to replace the north, south, etc with N S in address fields.
If I have
list = {'NORTH':'N','SOUTH':'S','EAST':'E','WEST':'W'} address = "123 north anywhere street"
Can I for iterate over my dictionary values to replace my address field?
for dir in list[]: address.upper().replace(key,value)
I know i'm not even close!! But any input would be appreciated if you can use dictionary values like this.
To replace all the multiple substrings in a string based on a dictionary. We can loop over all the key-value pairs in a dictionary and for each key-value pair, replace all the occurrences of “key” substring with “value” substring in the original string using the regex.
The replace() method returns a copy of the string where the old substring is replaced with the new substring. The original string is unchanged. If the old substring is not found, it returns the copy of the original string.
The keys of a dictionary can be any kind of immutable type, which includes: strings, numbers, and tuples: mydict = {"hello": "world", 0: "a", 1: "b", "2": "not a number" (1, 2, 3): "a tuple!"}
Python String | replace() replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.
address = "123 north anywhere street" for word, initial in {"NORTH":"N", "SOUTH":"S" }.items(): address = address.replace(word.lower(), initial) print address
nice and concise and readable too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With