开发者

Python - "\" character

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?


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)


backslash = '\\'

For build filesystem path use crossplatform:

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


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.


\ 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜