0

I'm working with a file that contains some lines with backslash characters, such as "moz\\123\\". I have each line then stored in a dictionary and later compared to the original line in the file. The problem is that Python inputs into the dictionary a key with double the number of backslashes (instead of "moz\\123\\", I get "moz\\\\123\\\\") so when doing the comparison between the original line and the key in the dictionary, the original cannot be found because the key is different. How can I handle this problem? Here is some code:

my_dict={}

def reader():
inputfile=open('<filepath>', 'r')
for line in inputfile:
    my_dict[line]=0
print(my_dict)

reader()

where filepath contains

the
here
moz\\12\\14
the\ 

and the print statement gives

{'here\n': 0, 'the\\': 0, 'the\n': 0, 'moz\\\\12\\\\14\n': 0}.
Moz
  • 15
  • 3
  • 3
    Python represents a backslash character with two backslashes. (Not always, but in your case it does.) The backslashes are probably not the problem, if you're getting KeyErrors there's most likely a different reason. Please post some code. – Aran-Fey Jul 17 '16 at 18:56
  • This is because symbols are being escaped. You might take a look at so called raw strings. However, as a quick 'n' dirty workaround you could apply a `str.replace()` as described [here on SO](http://stackoverflow.com/a/7262918/3991125) – albert Jul 17 '16 at 18:57
  • 1
    `print('moz\\\\12\\\\14') -> moz\\12\\14` try it, then remember that backslashes are used for escape characters like `\n`, to have a literal backslash it needs to be backslash escaped. – Tadhg McDonald-Jensen Jul 17 '16 at 19:26

1 Answers1

0

Or simply try to change "\\" to "//", where filepath contains :

the
here
moz//12//14
the/

the code :

my_dict={}

def reader():
   inputfile= open('<filepath>', 'r')
   for line in inputfile:
      my_dict[line.strip()]=0
   return my_dict

print(reader())

the result :

{'the/': 0, 'the': 0, 'moz//12//14': 0, 'here': 0}

because when you write :

print("hello\\bonjour\\")

it gives :

hello\bonjour\