shaggs
shaggs

Reputation: 620

Use dict to replace word in string

Im trying to replace one part of my string using a dict.

s  = 'I am a string replaceme'

d = {
'replaceme':  'replace me'
 }

Ive tried lots of variations like

s = s.replace(d, d[other])

That throws an error being name error: name 'other' is not defined. If I do

s = s.replace('replaceme', 'replace me')

It works. How can i achive my goal?

Upvotes: 2

Views: 43

Answers (3)

Hai Vu
Hai Vu

Reputation: 40698

Here is a different approach: using reduce:

s  = 'I am a string replaceme'
d = {'replaceme': 'replace me', 'string': 'phrase,'}
s = reduce(lambda text, old_new_pair: text.replace(* old_new_pair), d.items(), s)
# s is now 'I am a phrase, replace me'

Upvotes: 0

Alessandro Da Rugna
Alessandro Da Rugna

Reputation: 4695

You have to replace each KEY of your dict with the VALUE associated. Which value holds the other variable? Is it a valid KEY of your substitutions dict? You can try with this solution.

for k in d:
    s = s.replace(k, d[k])

Each key in dictionary is the value to be replaced, using the corresponding VALUE accessed with d[k].
If the dictionary is big the provided example will show poor performances.

Upvotes: 2

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

You could split the string and rejoin:

s = 'I am a string replaceme'

d = {
'replaceme':  'replace me'
 }

print(" ".join([w if w not in d else d[w] for w in s.split(" ")]))

That won't match substrings where str.replace will, if you are trying to match substring iterate over the dict.items and replace the key with the value:

d = {
'replaceme':  'replace me'
 }

for k,v in d.items():
    s = s.replace(k,v)

print(s)

I am a string replace me

Upvotes: 0

Related Questions