Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare backslash in python

I have a set of strings that are read from a file say ['\x1\p1', '\x2\p2', '\x3\p3', ... etc.].

When I read them into variables and print them the strings displayed as ['\\x1\\p1', '\\x2\\p2', '\\x3\\p3', ... etc.]. I understand that the variable is represented as '\x1\p1', ... etc. internally, but when it is displayed it is displayed with double slash.

but now I want to search and replace the elements of this list in the sentence, i.e say if \x1\p1 is in the sentence "How are you doing \x1\p1" then replace '\x1\p1' with 'Y'. But the replace method does not work in this case! wonder why?

Let me explain further: my text file (codes.txt) has entries \xs1\x32, \xs2\x54 delimited by new line. so when I read it using

with open('codes') as codes:
    code_list = codes.readlines()

next, I do lets say code_list_element_1 = code_list[1].rstrip()

when I print code_list_element_1, it displays as '\\xs1\\x32'

Next, let me target string be target_string = 'Hi! my name is \xs1\x32'

now I want to replace code_list_element_1 which is supposed to be \xs1\x32 in the target_string with say 'Y'

So, I tried code_list_element_1 in target_string. I get False

Next, instead of reading the codes from a text file I initialized a variable find_me = '\xs1\x32'

now, I try find_me in target_string. I get True

and hence target_string.replace(find_me,"Y") displays what I want: "Hi! my name is Y"

like image 590
suzee Avatar asked Feb 14 '23 20:02

suzee


1 Answers

You are looking at a string representation that can be pasted back into Python; the backslashes are doubled to make sure the values are not interpreted as escape sequences (such as \n, meaning a newline, or \xfe, meaning the byte with value 254, hex FE).

If you are building new string values, you also need to use those doubled backslashes to prevent Python from seeing escape sequences where there are none, or use raw string literals:

>>> '\\x1\\p1'
'\\x1\\p1'
>>> r'\x1\p1'
'\\x1\\p1'

For this specific example, not handling the backslashes properly actually results in an exception:

>>> '\x1\p1'
ValueError: invalid \x escape

because Python expects to find two hex digits after a \x escape.

like image 174
Martijn Pieters Avatar answered Feb 17 '23 10:02

Martijn Pieters