Home > other >  Replace space with underscore in string pickle
Replace space with underscore in string pickle

Time:10-22

I have data in pickle format and inside the file is dictonary with several file names in the key which are like below

Key Type Size Value

22 NN_64_100_0.txt float 1 nan

The key has several names with the spaces in-between. I want to replace that with underscore like below.

 22_NN_64_100_0.txt 

I tried this way like below:

with open('/data/record.pickle', 'rb') as f:
    data = pickle.load(f)    

    {data.replace(' ', '_'): v for k, v in data.items()}

But it didn't work

Can anyone help how to make it ?

CodePudding user response:

Use Regex to replace several spaces into underscores

import re

with open('/data/record.pickle', 'rb') as f:
    data = pickle.load(f)    
    {re.sub(r' ', '_', k): v for k, v in data.items()}

Tell me if its not okay for you...

  • Related