EOL while scanning string literal even using r [duplicate] - python

This question already has answers here:
Why can't Python's raw string literals end with a single backslash?
(13 answers)
Closed 2 years ago.
I am trying to define a name for a long server folder path below. May I know why I still get "EOL while scanning string literal" error? Many thanks.
path= (r '\\hbap.adroot.abb\HK\Finance\00210602\AMH_A2R\1KY\Drv Reengine\Python\')

Its not allowed to put a space between the 'r' and the string. However i suggest just doubling the backslashes to escape them like this:
path= ("\\\\hbap.adroot.abb\\HK\\Finance\\00210602\\AMH_A2R\\1KY\\Drv Reengine\\Python\\")
Alternativly, you can just leave out the backslash at the end and do this:
path= (r"\\hbap.adroot.abb\HK\Finance\00210602\AMH_A2R\1KY\Drv Reengine\Python")
All is good, as long as you escape the backslashes and dont have the string ending with a \ (except if that ending backslash is doubled)

Related

Why print returns \\, not a escape character \ in Python [duplicate]

This question already has answers here:
How to fix "<string> DeprecationWarning: invalid escape sequence" in Python?
(2 answers)
Closed 7 months ago.
The below code prints the emoji like, this 😂 :
print('\U0001F602')
print('{}'.format('\U0001F602'))
However, If I use \ like the below, it prints \U0001F602
print('\{}'.format('U0001F602'))
Why the print('\{}'.format()) retunrs \\, not a escape character, which is \?
I have been checking this and searched in Google, but couldn't find the proper answer.
Referring to String and Bytes literals, when python sees a backslash in a string literal while compiling the program, it looks to the next character to see how the following characters are to be escaped. In the first case the following character is U so python knows its a unicode escape. In the final case, it sees {, realizes there is no escape, and just emits the backslash and that { character.
In print('\{}'.format('U0001F602')) there are two different string literals '\{}' and 'U0001F602'. That the first string will be parsed at runtime with .format doesn't make the result a string literal at all - its a composite value.
>>> print('\{}'.format('U0001F602'))
\U0001F602
This is because you are giving {} as an argument to .format function and it only fills value inside the curly braces.
ANd it is printing a single \ not double \

How to make python 3 understand double backslash? [duplicate]

This question already has answers here:
How to fix "<string> DeprecationWarning: invalid escape sequence" in Python?
(2 answers)
Closed 1 year ago.
So, as SO keeps suggesting me, I do not want to replace double backslashes, I want python to understand them.
I need to copy files from a windows distant directory to my local machine.
For example, a "equivalent" (even if not) in shell (with windows paths):
cp \\directory\subdirectory\file ./mylocalfile
But python does not even understand double backslashes in strings:
source = "\\dir\subdir\file"
print(source)
$ python __main__.py
__main__.py:1: DeprecationWarning: invalid escape sequence \s
source = "\\dir\subdir\file"
\dir\subdir
ile
Is Python able to understand windows paths (with double backslashes) in order to perform file copies ?
You can try this also:
source = r"\dir\subdir\file"
print(source)
# \dir\subdir\file
You can solve this issue by using this raw string also.
What we are doing here is making "\dir\subdir\file" to raw string by using r at first.
You can visit here for some other information.
raw strings are raw string literals that treat backslash (\ ) as a literal character. For example, if we try to print a string with a “\n” inside, it will add one line break. But if we mark it as a raw string, it will simply print out the “\n” as a normal character.

How to read CSV file from a Windows path? [duplicate]

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 2 years ago.
When setting a string to a filepath in Python for WIndows, does it need to be formatted as:
C:\\Users\\
Or do escapes not apply on Windows? My script is currently giving me something like "Non-ASCII character" at the line import os, so I can't really test this.
Try adding an "r", do as below:
path = r"C:\mypaht\morepaht\myfie.file"
Short answer: Use forward slash instead as suggested by gnibbler.
On using raw strings:
Using a raw string usually works fine, still you have to note that r"\"" escapes the quoute char. That is, raw string is not absolutely raw and thats the reason why you cant use backslash (or any odd number of backslashes) in the end of a string like '\' (the backslash would escape the following quote character).
In [9]: a=r'\\'
In [10]: b=r'\\\'
File "<ipython-input-10-9f86439e68a3>", line 1
b=r'\\\'
^
SyntaxError: EOL while scanning string literal
In [11]: a
Out[11]: '\\\\'
You should not construct file paths that way. Its not portable and error prone.
Use the join() function from os.path
import os.path
path = os.path.join('C:', 'Users', 'name')

Trailing slash in a raw string [duplicate]

This question already has answers here:
Why can't I end a raw string with a backslash? [duplicate]
(4 answers)
Why can't Python's raw string literals end with a single backslash?
(14 answers)
Closed 8 years ago.
Just a quick silly question. How do I write a trailing slash in a raw string literal?
r = r'abc\' # syntax error
r = r'abc\\' # two slashes: "abc\\"
You can't. A raw string literal can't end with an odd number of backslashes (langref; last paragraph of that section). You can, howerver, write a raw string literal without the backslash, and write the final backslash as an ordinary string literal:
r = r'abc' '\\'
Adjacent string literals are implicitly concatenated by the parser.
Raw string literals are parsed in exactly the same way as ordinary string literals; it’s just the conversion from string literal to string object that’s different. This means that all string literals must end with an even number of backslashes; otherwise, the unpaired backslash at the end escapes the closing quote character, leaving an unterminated string.

backslash in Yaml string [duplicate]

This question already has answers here:
Why do backslashes appear twice?
(2 answers)
Closed 8 years ago.
So I'm using yaml for some configuration files and py yaml to parse it.
For one field I have something like:
host: HOSTNAME\SERVER,5858
But when it gets parsed here what I get:
{
"host": "HOSTNAME\\SERVER,5858"
}
With 2 backslashes. I tried every combination of single quotes, double quotes, etc.
What's the best way to parse it correctly ?
Thanks
len("\\") == 1. What you see is the representation of the string as Python string literal. Backslash has special meaning in a Python literal e.g., "\n" is a single character (a newline). To get literal backslash in a string, it should be escaped "\\".
You aren't getting two backslashes. Python is displaying the single backslash as \\ so that you don't think you've actually got a \S character (which doesn't exist... but e.g. \n does, and Python is trying to be as unambiguous as possible) in your string. Here's proof:
>>> data = {"host": "HOSTNAME\\SERVER,5858"}
>>> print(data["host"])
HOSTNAME\SERVER,5858
>>>
For more background, check out the documentation for repr().

Categories