1

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 ..

2
  • 6
    There's no backslash in that string. \n is an escape sequence that's parsed as a newline character. Commented Dec 19, 2021 at 19:35
  • 2
    '\n' does not contain a backslash. It is one character. You can test this yourself with ord('\n') Commented Dec 19, 2021 at 19:37

1 Answer 1

3
# 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('\\'))
Sign up to request clarification or add additional context in comments.

3 Comments

thank you very much for your explaination I realy apreaciate it <3
isn't there any trick to add '\' to a string (e.g): text = 'n' ; text[0] = '\'
Strings are immutable, you can't modify them by subscripting the way you can a list. Do text = '\\' + text if you want to prepend a '\' to text.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.