0

I am trying to solve the already asked question link with one liner. But not getting expected.

d={'Old': 'New', 'old': 'new'}
strr='Old, not old'

Attempt

[ strr.replace(k,v) for k,v in d.items() if k in strr] 
Out[19]: ['New, not old', 'Old, not new']

Expected

New, not new
PIG
  • 599
  • 3
  • 13

1 Answers1

5

Because you are using a list generator that is constructing a list of strings where each string contains only one replace from the dictionary. Just use ordinary loops to replace everything word-by-word:

d={'Old': 'New', 'old': 'new'}
strr='Old, not old'

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

strr

will return:

'New, not new'

vurmux
  • 9,420
  • 3
  • 25
  • 45
  • is it not possible in one liner ? – PIG May 21 '19 at 06:05
  • 1
    Well, technically you can write `for k, v in d.items(): strr = strr.replace(k, v)` in one line. But it is bad code and you should avoid this. It is ok to have several lines even for simple task, especially if it improves code readability. – vurmux May 21 '19 at 09:15