3

I'm newbie in Python. I'm trying to insert in a string a "\" character, but if i declare it like this, it takes \" as a " character. I also tried to declare, e.g. fname='\\' but it does not work.

What I mean to do is to add to a path e:\\Others\Contacts the string \<filename>.

May anyone help me?

5
  • 2
    Why downvote? I see nothing wrong with that question Commented Aug 12, 2011 at 12:22
  • 1
    Hi Joker, welcome to StackOverflow. Please take a second to learn about code formatting in the edit box. Paste your code as-is, and then highlight it and press Ctrl-K to format it as code. Otherwise the results can be unexpected, especially with regards to backslashes. Commented Aug 12, 2011 at 12:23
  • @Miro: Probably because of the problematic formatting. For example, he wrote fname='\\', but it was rendered as fname='\', and now it's hard to tell what his actual problem is. I agree that downvoting this is not helpful at all (and it doesn't even change anything since he is still at 1 rep). Commented Aug 12, 2011 at 12:25
  • was my first post on stackoverflow ;) Commented Aug 12, 2011 at 12:34
  • For general information- if you ever need to use double backslashes (for a paragraph end in LaTeX for example), you need to escape both. Use "\\\\". Commented Aug 12, 2011 at 14:38

4 Answers 4

11
backslash = '\\'

You can also use raw string literals. Note that there's no way to have a backslash at the end of a raw string literal though.

path = r'e:\Others\Contacts'

However, instead of fiddling with backslashes, you should use os.path.join to concatenate paths:

import os.path
p = os.path.join('e:', 'Others', 'Contacts', filename)
Sign up to request clarification or add additional context in comments.

Comments

1
backslash = '\\'

For build filesystem path use crossplatform:

>>> import os.path
>>> os.path.join("e:", "Others", "Contacts")
'e:\Others\Contacts'

Comments

1

To add to a file path you should not try to do this by hand but use the standard library. The module that you should look at is os.path. To add directoires to an existing path look at the join method.

Comments

1

\ is the escape character. \' means '. Think about it, how else would you represent ' in a single quoted string?

To use a \ character, you need to have \\ in the string.

2 Comments

Oops.I totally forgot about that one. Updated.
it didn't worked, but thank you anyway: i used join method explicated by pihagh;)

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.