-2

I want to replace a substring from a string of values.However, replacing a single string without any group of strings is not easy.

I have data like this:

S.no      Name                     Expected Result
------    ----------------------   ----------------------
1         2341 blvd                2341 Boulevard
2         648 s Kingston rd        648 S Kingston Road
3         sw Beverly st            SW Beverly Street
julianfperez
  • 1,726
  • 5
  • 38
  • 69
  • 1
    It would be recommended that the solution, that you tried, to be included in the problem description. This would help others to understand the issue and detect possible errors or suggest new solutions. – julianfperez May 20 '18 at 08:20

1 Answers1

1
def wordreplace(s, d):
    """Replaces words in string by dict d. # Thank you @Patrick Artner
    for improving dict call to d.get(w, w)!"""
    return ' '.join([ d.get(w, w) for w in s.split()])


# this was my old version:
# def wordreplace(s, d):
#    """Replaces words in string by dict d."""
#    return ' '.join([ d[w] if w in d else w for w in s.split()])

d = {'blvd': 'Boulevard', 'st': "Street", 'sw': 'SW', 's': "S", 'rd': '
Road'}

s1 = "2341 blvd"

s2 = "648 s Kingston rd"

s3 = "sw Beverly st"

wordreplace(s1, d)
# '2341 Boulevard'

wordreplace(s2, d)
# '648 S Kingston Road'

wordreplace(s3, d)
# 'SW Beverly Street'

s.split() splits by default by a single space thus returns list of words of the string s. Each of the word is loaded into variable w. The for w in s.split() part of the list expression. The part before the for determines what is collected in the resulting list.

if w in d means: Test whether the word is in the given replacer-dictionary d. It looks into d.keys() the keys of the dictionary. When found, it returns the dictionary value d[w]. else it returns the word itself w.

The resulting list ist joined using the ' ' as joining element, thus the list of words is re-transformed into a string.

List expressions are very handy and lead often to such one-line functions. So heavily recommend you to learn them.

Instead of typing all key - values into the dictionary form, you can also do:

keys = [ # list here all keys ]
vals = [ # list here all corresponding values in the right order ]
d = {k: vals[i] for i, k in enumerate(keys)}

So again, you can use the power of list expressions to generate with them a dictionary.

# abstract it to a function
def lists2dict(keys_list, vals_list):
    return {k, vals_list[i] for i, k in enumerate(key_list)}

# and then call:
d = lists2dict(keys, vals)
Gwang-Jin Kim
  • 9,303
  • 17
  • 30
  • `d[w] if w in d else w` ==> `d.get(w, w)` - see [why `dict.get(key,'')` instead of `dict[key]`](https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey) - nice answer – Patrick Artner May 20 '18 at 11:07
  • Thank you, Patrick! True! I have seen dict.get(), but fell back into old habits :) - I'll use dict.get(), too, in future - always! ;) – Gwang-Jin Kim May 20 '18 at 22:09