-3

I have specific letters ’ that I want to remove from the string values in a dictionary wherever they are found. However, I don't know why a single change on a specific key works, while when looping on the whole dictionary doesn't.

The loop used is:

data_nv = {
    '00254325': 'remove something and something else etc etc ’, do this',
    '00348956': 'have fun here and here the’n get this and that'
}

for key in data_nv:
    if '’' in data_nv[key]:
        data_nv[key].replace('’', ' ')

If I do a replacement like the one below it works.

data_nv['00254325'].replace('’', ' ')
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
ChakiO
  • 5
  • 1
  • 3
    `replace()` returns a new string. It does not modify the original. – 001 Aug 03 '20 at 15:31
  • Does this answer your question? [String replace doesn't appear to be working](https://stackoverflow.com/questions/26943256/string-replace-doesnt-appear-to-be-working) – mkrieger1 Aug 03 '20 at 15:35
  • 1
    The proper solution would be to fix whatever produced that mojibake in the first place. It looks like you are importing UTF-8 into a Windows-1252 context without properly translating it, or possibly improperly translating content which is already UTF-8 on the assumption that its encoding is Windows-1252 (or some other legacy 8-bit encoding). If you have literally the bytes 0xE2 0x80 0x99 that's UTF-8 for a single quote [U+2019](https://www.fileformat.info/info/unicode/char/2019/index.htm). – tripleee Aug 03 '20 at 15:35
  • Better: https://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method-do-anything-unless-you-assign-its-out – mkrieger1 Aug 03 '20 at 15:36
  • Yes triplee, I noticed I have this encoding/decoding problem with my data that I need to fix – ChakiO Aug 03 '20 at 15:50

2 Answers2

2

str.replace returns a value with the replacement happend. You need to store the value back into the dictionary:

data_nv={'00254325': 'remove something and something else etc etc ’, do this', 
         '00348956': 'have fun here and here the’n get this and that'}

for key in data_nv:
    if '’' in data_nv[key]:
        # store replaced value back in dict under key
        data_nv[key] = data_nv[key].replace('’', ' ')

print(data_nv)

Output:

{'00254325': 'remove something and something else etc etc  , do this',
 '00348956': 'have fun here and here the n get this and that'}
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Just found it,

We can use the re library like this:

for key in data_nv:
    if '’' in data_nv[key]:
        data_nv[key]=re.sub(r'’',' ',data_nv[key])
ChakiO
  • 5
  • 1