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().
Related
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 \
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 2 years ago.
Say I assign variable
x = '\\dnassmb1\biloadfiles_dev\Workday'
print(x)
Output:
'\\dnassmb1\x08iloadfiles_dev\\Workday'
I would like to know why it's changing to "x08.." specifically and how to avoid that automatic change and use string as it is. Thank you!
You are doing wrong.Backslash has a different meaning in pyhton while using in strings.
Backslashes are actually used to put some special character inside the string.
If you want to get the above string printed;
x = '\\\dnassmb1\\biloadfiles_dev\\Workday'
print(x)
If you got this, i am using an extra backslash everywhere where i want a backslash to be printed. This is because the first backslash indicates that what ever is going to come after it is just a part of the string and has no special meaning.
Use raw strings:
x = r'\\dnassmb1\biloadfiles_dev\Workday'
This will prevent python from treating your backslashes as escape sequences. See string and byte literals in the Python documentation for a full treatment of string parsing.
It's important to pay close attention to the difference between representation and value here. Just because a string appears to have four backslashes in it, doesn't mean that those backslashes are in the value of the string. Consider:
>>> x = '\\dnassmb1\biloadfiles_dev\Workday' # regular string
>>> y = r'\\dnassmb1\biloadfiles_dev\Workday' # raw string
>>> print(x); print(y)
\dnassmbiloadfiles_dev\Workday
\\dnassmb1\biloadfiles_dev\Workday
Here, x and y are both just strings, once Python has parsed them. But even though the parts inside the quotes are the same, the bytes of the string are different. In y's case, you see exactly the number of backslashes you put in.
This question already has answers here:
How to write string literals in Python without having to escape them?
(6 answers)
Closed 7 months ago.
I know this is similar to many other questions regarding backslashes, but this deals with a specific problem that has yet to have been addressed. Is there a mode that can be used to completely eliminate backslashes as escape characters in a print statement? I need to know this for ascii art, as it is very difficult to find correct positioning when all backslashes must be doubled.
print('''
/\\/\\/\\/\\/\\
\\/\\/\\/\\/\\/
''')
\```
Preface the string with r (for "raw", I think) and it will be interpreted literally without substitutions:
>>> # Your original
>>> print('''
... /\\/\\/\\/\\/\\
... \\/\\/\\/\\/\\/
... ''')
/\/\/\/\/\
\/\/\/\/\/
>>> # as a raw string instead
>>> print(r'''
... /\\/\\/\\/\\/\\
... \\/\\/\\/\\/\\/
... ''')
/\\/\\/\\/\\/\\
\\/\\/\\/\\/\\/
These are often used for regular expressions, where it gets tedious to have to double-escape backslashes. There are a couple other letters you can do this with, including f (for format strings, which act differently), b (a literal bytes object, instead of a string), and u, which used to designate Unicode strings in python 2 and I don't think does anything special in python 3.
This question already has answers here:
How to fix "<string> DeprecationWarning: invalid escape sequence" in Python?
(2 answers)
Closed 4 years ago.
In the given example: "\info\more info\nName"
how would I turn this into bytes
I tried using unicode-escape but that didn't seem to work :(
data = "\info\more info\nName"
dataV2 = str.encode(data)
FinalData = dataV2.decode('unicode-escape').encode('utf_8')
print(FinalData)
This is were I should get b'\info\more info\nName'
but something unexpected happens and I get DeprecationWarnings in my terminal
I'm assuming that its because of the backslashes causing a invalid sequence but I need them for this project
Backslashes before characters indicate an attempt to escape the character that follows to make it into a special character of some sort. You get the DeprecationWarning because Python is (finally) going to make unrecognized escapes an error, rather than silently treating them as a literal backslash followed by the character.
To fix, either double your backslashes (not sure if you intended a newline; if so, double double the backslash before the n):
data = "\\info\\more info\\nName"
or, if you want all the backslashes to be literal backslashes (the \n shouldn't be a newline), then you can use a raw string by prefixing with r:
data = r"\info\more info\nName"
which disables backslashes interpolation for everything except the quote character itself.
Note that if you just let data echo in the interactive interpreter, it will show the backslashes as doubled (because it implicitly uses the repr of the str, which is what you'd type to reproduce it). To avoid that, print the str to see what it would actually look like:
>>> "\\info\\more info\\nName" # repr produced by simply evaluating it, which shows backslashes doubled, but there's really only one each time
"\\info\\more info\\nName"
>>> print("\\info\\more info\\nName") # print shows the "real" contents
\info\more info\nName
>>> print("\\info\\more info\nName") # With new line left in place
\info\more info
Name
>>> print(r"\info\more info\nName") # Same as first option, but raw string means no doubling backslashes
\info\more info\nName
You can escape a backslash with another backslash.
data = "\\info\\more info\nName"
You could also use a raw string for the parts that don't need escapes.
data = r"\info\more info""\nName"
Note that raw strings don't work if the final character is a backslash.
This question already has an answer here:
Why does printing a tuple (list, dict, etc.) in Python double the backslashes?
(1 answer)
Closed 5 years ago.
I am trying to assign
user = 'corp\adam'
Using python I am unable to create a user variable as desire.
Desired Output:
user
'corp\adam'
I don't want to print the variable. I need to store it.
In Python (and commonly in other programming languages too) the backslash character is used to denote special characters that could not be typed directly into a string. This is known as an escape sequence. To specify a literal backslash, use it twice:
user = 'corp\\adam'
Try a double backslash, i.e. corp\\adam. The first backslash denotes that the second one has to be evaluated like a normal character, not as another escape character.
The backslash character acts as an escape when the next character is an ASCII or Python special escape character. Either escape the backslash with another backslash:
'corp\\adam'
or use a raw string (where backslash only escapes the quote character it doesn't even escape itself):
r'corp\adam'
You can use r'corp\adam' that way you tell Python it's a "raw" string and the backslash will not be used to escape other characters.
From the docs:
Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters.