at_Root
at_Root

Reputation: 71

how I can replace backslashes in python

I simply wanna replace the backslash but I can't , I searched every where but nothing found

I tried:


mystr = "\n"

mystr.replace("\\",'x') #nothing happened

print(mystr.startswith('\\')) #False

print(ord('\')) #EOL_Error

print(ord(mystr[0]) == ord('\\')) #False

can any one help me pleas ..

Upvotes: 1

Views: 1170

Answers (1)

Samwise
Samwise

Reputation: 71434

# This string contains no backslashes; it's a single linebreak.
mystr = "\n"
# Hence this does nothing:
mystr.replace("\\", 'x') 
# and this is False:
print(mystr.startswith('\\'))

# This is a syntax error because the \ escapes the '
print(ord('\')) #EOL Err

# This is still False because there's still no '\\` in mystr
print(ord(mystr[0]) == ord('\\')) #False

If you use the \\ escape consistently you get the results you're looking for:

# This string contains a backslash and an n.
mystr = '\\n'
# Now this prints "xn":
print(mystr.replace('\\', 'x'))
# and this is True:
print(mystr.startswith('\\'))

# This prints 92
print(ord('\\'))

# This is also True:
print(ord(mystr[0]) == ord('\\'))

You can define mystr as a raw string (making '\n' a literal \ followed by n), but this doesn't work for strings like '\' because even in a raw string, the \ escapes any quotation mark immediately following it. For a string ending in \ you still need to use a normal escape sequence.

mystr = r'\n'
print(mystr.replace('\\', 'x'))
print(mystr.startswith('\\'))

print(ord('\\'))
print(ord(mystr[0]) == ord('\\'))

Upvotes: 3

Related Questions