Reputation: 1597
I'm trying to build a string dynamically with the following code
output = "".join(["network", "\", "account"])
The escaped result should be something like network\account
How can do this in Python3 without running into this errors
File "<stdin>", line 1
"".join(["network", "\", "account"])
^
SyntaxError: invalid syntax
Upvotes: 1
Views: 4259
Reputation: 11878
Raw strings is another way (someone already posted an answer using an escape character).
Precede the quotes with an r:
r'network\account
Edit:
I realise that this doesn't actually work with your example using a single backslash,
I had posted:
output = "".join(["network", r"\", "account"])
but according to Python docs.
Even in a raw literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw literal cannot end in a single backslash (since the backslash would escape the following quote character).
https://docs.python.org/3/reference/lexical_analysis.html?highlight=raw%20strings
Upvotes: 3
Reputation: 41
In Python strings, the backslash "\" is a special character, also called the "escape" character, so use '\\' for "escape" character
output = "".join(["network", "\\", "account"])
Upvotes: 0
Reputation: 241
Escape the backslash:
output = "".join(["network", "\\", "account"])
Upvotes: 2