how to replace double back slash with single back slash in python - python

buf= 'b"\\\x00\\\x00\\\x1a\\\x00/H\\\x00\\\x00\\\xf8f\\\x14'""'
I need:
buf= 'b"\x00\x00\x1a\x00/H\x00\x00\xf8f \x14'""'
I tried: buf=buf.replace("\\","\")
But I am getting error: SyntaxError: EOL while scanning string literal

Make sure to escape each backslash with another backslash:
buf=buf.replace("\\\\","\\")
Or, you can use raw strings:
buf=buf.replace(r"\\",r"\")

You have to escape \ with a \. So replacing \ becomes \\ and replacing \\ becomes \\\\
buf= 'b"\\x00\\x00\\x1a\\x00/H\\x00\\x00\\xf8f\\x14'""
buf=buf.replace("\\\\","\\") # give b"\x00\x00\x1a\x00/H\x00\x00\xf8f\x14

in your code
buf=buf.replace("\\","\")
the first backslash will consider as an escape-sequence and will read the next character with special meaning. so in this stage "\" it will skip the second " so it will raise
SyntaxError: EOL while scanning string literal
replace your code with
buf=buf.replace(r"\\",r"\")
here 'r' is used to read the string completely,it will skip/avoid the escape sequances

Related

How to replace "\" with "\\" in python?

How to replace "\" with "\\" in python(type string)? I tried line = line.replace("\", "\\"), but it gives error SyntaxError: unexpected character after line continuation character
In Python strings, \ is an escape, meaning something like, "do something special with the next character." The proper way of specifying \ itself is with two of them:
line = line.replace("\\", "\\\\")
Funny enough, I had to do the same thing to your post to get it to format properly.
To replace \ with \\ in a Python string, you must write \\ in the Python string literal for each \ you want. Therefore:
line = line.replace("\\", "\\\\")
You can often use raw strings to avoid needing the double backslashes, but not in this case: r"\" is a syntax error, because the r modifier doesn't do what most people think it does. (It means both the backspace and the following character are included in the resulting string, so r"\" is actually a backslash followed by a quote, and the literal has no terminating quote!)

Why do I only have to escape the last backslash in a string literal?

I have the following Python code:
localExtractpath = "D:\Python\From 0 to 1\Excel\"
if os.path.exists(localZipPath):
print("Cool! '" + localZipPath + "' exists...proceeding...")
This gives me the error:
File "", line 2
localExtractpath = "D:\Python\From 0 to 1\Excel\"
^
SyntaxError: EOL while scanning string literal
When I escape the last \ in the string, the code works. Why do I only have to escape the last \?
Why do I only have to escape the last \?
Because only after the last \ there is a symbol (") which together with \ forms an escape sequence — \" (escaping the role of the quote symbol " as a string terminator).
If \ with subsequent symbol(s) don't form an escape sequence, it's kept as is, i.e. as the backslash symbol itself.
(In your case neither \P, nor \F and nor \E form an allowed escape sequence, so the symbol \ itself is interpreted literally — as is.)
An (unsolicited) solution:
Use forward slashes (/) instead of backslashes (\)
(all Windows system calls accept them, too):
localExtractpath = "D:/Python/From 0 to 1/Excel/"
The last backslash in "D:\Python\From 0 to 1\Excel\" is escaping your ending quotation mark, so in the eyes of the interpreter, your string is unterminated. In fact, you have to escape all your backslashes if you want to use the literal backslash in your string:
"D:\\Python\\From 0 to 1\\Excel\\"
Other answers are right: you should escape all your backslashes and, even better, you should use forward slash for path elements (you can even take a look at the pathlib library).
But to answer specifically your question on why the issue lies only in the last one and not in the previous backslashes, you should take a look at the definition of string literals.
You will see that there is a (short) list of characters for which the backslash makes something particular. For the rest, the backslash is taken as itself.
For instance "\n" is interpreted not as a string with two characters (\ and n) but as a string with only a single line-feed character.
That is not the case with "\P", "\F" or "\E" which are two characters each since they don't have a specific meaning.
\" and \' are particular in that they allow to respectively insert a " or ' character in a string literal delimited by this same character.
For example, 'single: \', double "' and "single: ', double: \"" are two ways to define the single: ', double " string literal.

python raw string notation throwing error with trailing slash

I'm trying to set a path to a string variable in python using raw string notation and am getting an error with the trailing slash:
datapath = r'C:\path\to\my\data\'
gives me an "EOL while scanning string literal" error
I thought raw string notation was supposed to make everything in the string literal. Can someone explain this to me?
Thanks
There's an exception for the end quote of the string because:
C:\path\to\my\data\'
sees ' literally since the previous backslash isn't seen as an escape char, so string parsing continues.
So as frustrating as it is, you have to do r'C:\path\to\my\data\\'
The documentation defines a string literal in this way:
stringliteral ::= [stringprefix](shortstring | longstring)
You're using the r stringprefix.
Then we have these definitions for characters in the strings:
shortstringchar ::= <any source character except "\" or newline or the quote>
longstringchar ::= <any source character except "\">
where you will notice that the backwards slash is not one of the characters allowed in a shortstring or a longstring.

SyntaxError: EOL while scanning string literal while using backslash escape

I know this is a noob question, but new to Python and trying to understand the following:
Why does the backslash escape work without error here:
>>> print "this is \\\ a string"
this is \\ a string
But when I try:
>>> print "\\\"
I get:
SyntaxError: EOL while scanning string literal
The first backslash escapes the second backslash, and the third escapes the double quote, which then fails to terminate the string. You need either print "\\\\" or print "\\\"", depending on what output you are actually trying to get. (The first will print \\ and the second will print \".)
Your first \ escapes your second \. Now the third \ waits for escaping another character but instead gets ' and escapes it. That's why it shows this error. This is the same error you will get if you try to do this
>>> print 'abc # Line ended while scanning string
In this case
>>> print "this is \\\ a string"
The third \ gets a space character which is not a special character. Hence third \ does not escape anything and is the part of the string.
When you do :
print "\\\"
First \ covers the second one and third one covers the " (quote itself). So its like python does not see the ending quotes , so you get the errror.
Just a further note on what has already been mentioned, each time you use a backslash it consumes the character following it. As you probably know, some have special meaning such as \t would insert a tab character. As you've seen, \\ is designed to show the backslash.
What Python also lets you do is prefix any string with r which is used to mean disable the escape mechanism inside the string. For example in your first example, adding the r would display all three backslashes 'as is'.
print r"this is \\\ a string"
this is \\\ a string
But be warned, even this trick will fail if you try your second example. You still need to avoid a backslash in the last character of a string:
print r"\\\"
SyntaxError: EOL while scanning string literal
It is because you have three backslashes , so the first two backslash indicate an escaped backslash , and the next backslash is used to escape the quotes, and hence there are no real ending quotes for your string causing the issue.
In the first string, the third backslash does not escape anything as it appears before a space which is not a special character and hence it gets printed.
If you do -
print "\\\ "
it may work (worked for me in python 3.4)
My version -
>>> print("\\\ ")
\\
Without space -
>>> print("\\\")
File "<stdin>", line 1
print("\\\")
^
SyntaxError: EOL while scanning string literal

Replace '\' character in python

I don't know why i can't find it, but i wanted to replace the special character '\' in python.
I have a String within i have '\' characters but i confident find the solution, to replace it with '-'.
This is what happening while i am trying to replace,
>>> x = 'hello\world'
>>> x
'hello\\world'
>>> x.replace('\', '-')
File "<stdin>", line 1
x.replace('\', '-')
SyntaxError: EOL while scanning string literal
EDIT:
Do try this it in the eclipse IDLE
x = 'hello\world'
print x
x.replace('\\', '-')
print x
Output:
hello\world
hello\world
You need to escape it with another backslash:
x.replace('\\', '-')
Backslashes are special, in that they are used to introduce non-printing characters like newlines into a string.
It's also how you add a ' character to a '-quoted string, which is what Python thinks you were trying to do. It sees \' and interprets as a literal quote within the string, rather than letting the ' end the string. Then it gets to the end of the string and finds EOL ("end of line") before the end of the string.
To introduce a real backslash, you need to double it. You can see that Python itself did this when printing the representation of your initial string here:
>>> x
'hello\\world'
Note the double backslash.
You ought to use a double backslash when specifying your string in the first place. The reason that doesn't need it is that \w is not a special character, so it gets interpreted as a literal backslash and a w. Had you said 'Hello\now' you would have a string with a newline in it.
You could have also marked the string as a "raw" string by prepending it with r as in r'hello\world'. This marks the string as not being eligible for any substitutions of special characters.
According to docs:
The backslash (\) character is used to escape characters that
otherwise have a special meaning, such as newline, backslash itself,
or the quote character.
You need to escape backslash with another backslash:
x.replace('\\', '-')
This \' is interpreted as a special character. Escape it:
x.replace('\\', '-')
in python your string
x = 'hello\world'
is replaced as x = "hello\world"
so to achieve u have to write
x.replace('\\','-')

Categories