1

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
1
  • 1
    If this is about file system paths, you might consider using os.path.join or similiar tools from the os library - this will help you keep things tidy in case of operating system switches. Commented Oct 2, 2019 at 7:41

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Worked in raw r'network\account but failed when used in join. Going with @sami-rouhe answer instead for this implementation
Yes, I realised that, and posed a link to the python docs explaining why. I learned something myself today. Raw strings can still be handy if its not just a single backslash.
2

Escape the backslash:

output = "".join(["network", "\\", "account"])

Comments

0

In Python strings, the backslash "\" is a special character, also called the "escape" character, so use '\\' for "escape" character

output = "".join(["network", "\\", "account"])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.