-2

How to append \ character to the start of the string in python, it throws an error saying

SyntaxError: EOL while scanning string literal

I need to append \ whenever underscore is seen in the string

for example:

__x_a\_\_x_a this needs to be done only for the initial underscores

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

2 Answers2

2

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
wim
  • 338,267
  • 99
  • 616
  • 750
1

You can use re.sub

>>> import re
>>> s = "__x_a" 
>>> new_s = re.sub(r'^_*', lambda x: x.group().replace('_', '\_'), s)
>>> print(new_s)
\_\_x_a
Sunitha
  • 11,777
  • 2
  • 20
  • 23