Python: Trailing backslash in raw strings [duplicate] - python

This question already has answers here:
Why can't Python's raw string literals end with a single backslash?
(13 answers)
Closed 7 months ago.
The current Python grammar doesn't allow one to output a trailing \ in a raw string:
>>> print(r'a\b\c\')
SyntaxError: EOL while scanning string literal
On the contrary, you can write Bash like this:
echo 'a\b\c\'
I understand what the doc is saying. I wouldn't feel strange if an expression '\' fails because the backslash is escaping the quote. What I'm questioning is r'\': Aren't raw strings meant to be raw (which means backslashes in the string are taken literally)?
Do we have to write r'a\b\c' + '\\' or 'a\\b\\c\\' to make a string literal a\b\c\ in Python? I couldn't see how this is Pythonic.

From the documentation,
Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.

The limitation is due to the fact that you need someway to include a ' inside a raw string. Otherwise there is no way to put bob said "I'm not hungry" in a string.
So you end up in weird situation where you need an escape character for this case. So in raw strings you escape a ' with a \ and yes the \ stays in the string.
So r'bob said "I\'m not hungry"' it is!!

When you write print(r'\'), Python understand \' in that statement as a character. Because of that python raised syntax error because the there is a incomplete string inside print function.
For an example if you need to print i am "free" man , you should write
print("i am \"free\" man")

Related

Python assign "\" to a variable [duplicate]

When I write print('\') or print("\") or print("'\'"), Python doesn't print the backslash \ symbol. Instead it errors for the first two and prints '' for the third. What should I do to print a backslash?
This question is about producing a string that has a single backslash in it. This is particularly tricky because it cannot be done with raw strings. For the related question about why such a string is represented with two backslashes, see Why do backslashes appear twice?. For including literal backslashes in other strings, see using backslash in python (not to escape).
You need to escape your backslash by preceding it with, yes, another backslash:
print("\\")
And for versions prior to Python 3:
print "\\"
The \ character is called an escape character, which interprets the character following it differently. For example, n by itself is simply a letter, but when you precede it with a backslash, it becomes \n, which is the newline character.
As you can probably guess, \ also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.
See the Python 3 documentation for string literals.
A hacky way of printing a backslash that doesn't involve escaping is to pass its character code to chr:
>>> print(chr(92))
\
print(fr"\{''}")
or how about this
print(r"\ "[0])
For completeness: A backslash can also be escaped as a hex sequence: "\x5c"; or a short Unicode sequence: "\u005c"; or a long Unicode sequence: "\U0000005c". All of these will produce a string with a single backslash, which Python will happily report back to you in its canonical representation - '\\'.

Including \n in a string in python [duplicate]

This question already has answers here:
How can I put an actual backslash in a string literal (not use it for an escape sequence)?
(4 answers)
Closed 7 years ago.
How do i escape \n in a string in python.
How do i write out to stdin in python this string "abc\ndef" as one single input
Sys.stdout.write("abc\ndef")
current output
import sys
>>> sys.stdout.write("abc\ndef")
abc
def
I would like it to be abc\ndef
You should escape the backslash so that it's not treated as escaping character itself:
Sys.stdout.write("abc\\ndef")
Background
The backslash \ tells the parser that the next character is something special and must be treated differently. That's why \n will not print as \n but as a newline. But how do we write a backslash then? We need to escape it, too, resulting in \\ for a single backslash and \\n for the output \n.
Docs here, also see this SO question
Alternatively you can use "raw" strings, i.e. prefixing your strings with an r, to disable interpreting escape sequences is your strings:
Sys.stdout.write(r"abc\ndef")
As an alternative to escaping the backslash, you can disable backslash-escaping entirely by using a raw string literal:
>>> print(r"abc\ndef")
abc\ndef

Why does python allow escaping quotes in rawdata string? [duplicate]

This question already has answers here:
Why can't Python's raw string literals end with a single backslash?
(14 answers)
Closed 8 years ago.
I'm trying to understand why python has this unheard of behavior.
If I'm writing rawdata string, it is much more likely that I won't want escaping quotes.
This behavior forces us to write this weird code:
s = r'something' + '\\' instead of just 's = r'something\'
any ideas why python developers found this more sensible?
EDIT:
I'm not asking why it is so. I'm asking what makes this design decision, or if anyone finds any thing good in it.
The r prefix for a string literal doesn't disable escaping, it changes escaping so that the sequence \x (where x is any character) is "converted" to itself. So then, \' emits \' and your string is unterminated because there's no ' at the end of it.
The decision to disallow an unpaired ending backslash in a raw string is explained in this faq:
Raw strings were designed to ease creating input for processors (chiefly regular expression engines) that want to do their own backslash escape processing. Such processors consider an unmatched trailing backslash to be an error anyway, so raw strings disallow that. In return, they allow you to pass on the string quote character by escaping it with a backslash. These rules work well when r-strings are used for their intended purpose.

Replace \\ with \ in python [duplicate]

This question already has answers here:
python: replace a double \\ in a path with a single \
(3 answers)
Closed 8 years ago.
I Have a string having path of folder like below
>>> path
'\\\\sdgte\\ssdfdaa\\asfdsf'
I want to replace \\ with \ . I tried to replace but does not work as below
>>> path.replace('\\','\')
File "<input>", line 1
path.replace('\\','\')
^
SyntaxError: EOL while scanning string literal
Any Help will be highly appreciated.
There is no "\\" in the string. If you print it instead of looking at its representation you'll see the value that the string actually contains.
>>> print path
\\sdgte\ssdfdaa\asfdsf
You should use the escape charachter '\' to escape each \ in your string
path.replace('\\\\','\\')
you probably don't need to replace anything. \ is a special character in python that means "the next character, literally" in string literals. That is, if you want a string, containg a backslash, you'd probably type "\\":
>>> len('\\')
1
>>> print '\\'
\
>>> print '\\\\foo\\bar'
\\foo\bar
>>>
The reason you're getting that SyntaxError is the same reason you're seeing the doubled backslashes to begin with: backslash is the "escape" character, used to indicate the start of a special sequence, like "\n" for line feed, which would otherwise be difficult to represent in a string. The backslash character itself therefore has to be represented by a double backslash.
On the other hand, if you don't need to use any escape sequences within a string, you can preface the string with "r" instead of doubling the backslashes:
path.replace(r'\\', r'\')
path.replace(r'\\', '\\')
"r" indicates a "raw" string.
The problem you are running into, is that \ is an escape character. Instead of reading that as
replace '\\' with '\'
python is reading your argument as "replace the single backslash character with the single quotation mark character". The reason you are getting the error you are, is because python is ignoring your second single quotation mark because it thinks that is what you want it to do.
What you want is:
path.replace('\\\\', '\\')
you have to escape all backslashes because they are special.

Can '\' be in a Python string? [duplicate]

This question already has answers here:
How can I put an actual backslash in a string literal (not use it for an escape sequence)?
(4 answers)
Closed 8 years ago.
I program in Python in PyCharm and whenever I write '\' as a string it says that the following statements do nothing. For example:
Is there a way to fix this and make it work?
Thanks.
You need to double the backslash:
'/-\\'
as a single backslash has special meaning in a Python string as the start of an escape sequence. A double \\ results in the string containing a single backslash:
>>> print '/-\\'
/-\
If the backslash is not the last character in the string, you could use a r'' raw string as well:
>>> print r'\-/'
\-/
You need to scape them to be in the string, for example:
>>>s='\\'
>>>print s
\
You can also use the r (raw string) modifier in front of the string to include them easily but they can't end with an odd number of backslash. You can read more about string literals on the docs.

Categories

Resources