KZZ
KZZ

Reputation: 11

How to replace "\" with "\\"

I've a path from wx.FileDialog (getpath()) shows "c:\test.jpg" which doesn't works with opencv cv.LoadImage() which needs "\\" or "/"

So, I've tried to use replace function for example:

s.replace("\","\\"[0:2]),s.replace("\\","\\\"[0:2])

but none those works.

And, this command s.replace("\\","/"[0:1]) returns the same path, I don't know why.

Could you help me solve this easy problem.

ps, I'm very new to python

thank you so much. sorry about my grammar

Upvotes: 1

Views: 326

Answers (5)

Bobby
Bobby

Reputation: 11576

In Python you can use / independently from the OS as path separator (as RobertPitt pointed out, you can do this anyway).

But to answer your question, this should work:

str.replace("\\", "\\\\")

Upvotes: 0

RobertPitt
RobertPitt

Reputation: 57268

I think your looking for s.replace("\\","/")

Looking at the docs, and im not a Python programmer but its like so:

str.replace(old, new[, count])

So your do not need the 3rd parameter, but you need new and old obviusly.

s.replace("\\","/")

the reason we have \\ as because if we only had "\" this means that your escaping a quotation and your old parameter gets sent a " that's if python don't trigger and error.

you need to send a Literal backslash like \ so what actually gets sent to the interpreter is a single \

you will notice with SO syntax highlighter where the string is being escaped..

s.replace("\","\\"[0:2]) #yours                        "
s.replace("\\","/") #mine

http://en.wikipedia.org/wiki/Escape_character

Upvotes: 2

KKZ
KKZ

Reputation: 1

def onOpen(self, event): # wxGlade: MyFrame.<event_handler>
    dlg = wx.FileDialog(self, "Open an Image")
    if dlg.ShowModal() == wx.ID_OK:
        __imgpath__ = dlg.GetPath()
        print 'Selected:', dlg.GetPath()
        self.panel_2.LoadImage(cv.LoadImage(__imgpath__))

I don't know why, but it works with opencv.

output : "Selected: c:\test.jpg"

I'm sorry I didn't try it out first.

Upvotes: 0

Winston Ewert
Winston Ewert

Reputation: 45039

Its not entirely clear to me what you want to do with the paths, but there are a number of functions for dealing with them. You may want to use os.path.normpath() which will correct the slashes for whatever platform you are running on.

Upvotes: 0

Aaron Digulla
Aaron Digulla

Reputation: 328556

\ escapes the next character. To actually get a backslash, you must escape it. Use \\:

 s.replace("\\","/")

Upvotes: 4

Related Questions