Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can you write a str.replace() using dictionary values in Python?

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.

like image 207
user1947457 Avatar asked Jan 04 '13 11:01

user1947457


People also ask

Can we use Replace in dictionary Python?

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.

How does STR replace work in Python?

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.

Can dictionary values be a 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!"}

How do you replace text in text in Python?

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.


1 Answers

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.

like image 66
Django Doctor Avatar answered Oct 10 '22 06:10

Django Doctor