Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

string - python replace single backslash with double backslash

In python, I am trying to replace a single backslash ("") with a double backslash(""). I have the following code:

directory = string.replace("C:UsersJoshDesktop20130216", "", "")

However, this gives an error message saying it doesn't like the double backslash. Can anyone help?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No need to use str.replace or string.replace here, just convert that string to a raw string:

>>> strs = r"C:UsersJoshDesktop20130216"
           ^
           |
       notice the 'r'

Below is the repr version of the above string, that's why you're seeing \ here. But, in fact the actual string contains just '' not \.

>>> strs
'C:\Users\Josh\Desktop\20130216'

>>> s = r"fo"
>>> s            #repr representation
'f\o'
>>> len(s)   #length is 3, as there's only one `''`
3

But when you're going to print this string you'll not get '\' in the output.

>>> print strs
C:UsersJoshDesktop20130216

If you want the string to show '\' during print then use str.replace:

>>> new_strs = strs.replace('\','\\')
>>> print new_strs
C:\Users\Josh\Desktop\20130216

repr version will now show \\:

>>> new_strs
'C:\\Users\\Josh\\Desktop\\20130216'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...