A single backslash in Python is written like this:
"\\"
Various ways to convince yourself of this:
>>> len("\\")
1
>>> print("\\")
\
>>> "\\\\\\\\\\\\\\\\\\"[0]
'\\'
>>> chr(92)
'\\'
>>> '\N{REVERSE SOLIDUS}'
'\\'
The weirdness is because, since the backslash is the escape character, a backslash itself must be escaped.
So, to answer the question in the title:
How to append “\” to the start of the string in python
You can use:
mystring = "\\" + mystring
In your example case, which is escaping only leading underscores, try something like this:
>>> mystring = '__x_a'
>>> n = next((i for i,c in enumerate(mystring) if c != '_'), len(mystring))
>>> result = mystring.replace('_', r'\_', n)
>>> print(result)
\_\_x_a