I’m extracting the text ^[\d]{3}-[\d]{4}-[\d]{7}-[\d]{1}$ from a web element and want to append it to a Python list. However, after appending, it shows up as an escaped string:
Reason is that `\` is considered to be escape character. Historically this is probably coming from old unix and c days and since thats also where python came from, it is like that.
So, consider you want to have line feed in the string. You enter \n .. you wouldn’t want your string initialized in your code as something like this:
Computer does know that your intent is to have linefeed and tab in the string and handles it,
So, next, regex uses similar mechanism, eg escape sequences for placeholders to indicate a meaning. In this case, \d for “digit”. But because of how language works and your intention is to now use output escape sequences but escape sequence for regex and in order to show the user as string representation, regex escape needs to be escaped thus becoming \\ when you are visually inspecting that. Why ? Because if you would show that regex as it actually is, and copy paste it into another string in your code, it would not work because \d would be first considered as string escape sequence. So the visual part here adds the second slash to escape it to tell underlying compiler/interpreter to not consider that we want \d to be interpreted as escape code but a literal \d ..
Same stuff with windows path .. printing them out turns C:\foo\bar\ into C:\\foo\\bar\\ and because we want literal \ and not a start of escape sequence, visual representation of \ is \\..
TLDR;
Its character encoding method thats been used since dawn of time and escaping in visual representation of the data enables you to copypaste the actual value from one location to another without modifying the actual content.
And how to change the behaviour - define a new string class in python side that uses str as baseclass and overwrite dunder repr and dunder str to discard escaping of escape sequences and initialize your regex in python code to that type, not in robot .. But you are begging for nosebleed if you go that route.