[Tutor] string conversion according to the terminal

Evert Rol evert.rol at gmail.com
Thu Aug 12 12:44:24 CEST 2010


> Ok. I appreciate ur response and its gud somewhat... But we dont have only space=" " . this '\' rules also applies to '(' ')' and all that stuff also... so i was looking for the builtin function that fully converts it... Is there any one??

This may depend on your system, but generally, putting the complete filename between quotes ("some filename with ()") also works well; no need for escapes (unless your filename contains quotes itself).
Otherwise, you put the a.replace in a simple for loop that iterates through all special characters that need to be replaced.
Or you could look into regular expressions: re.sub can help.

Lastly, depending on your exact needs, Python may already take care of this anyway. Eg:
>>> import glob
>>> files = glob.glob("special*")
>>> files
['special name']
>>> f = open(files[0])
>>> f.read()
'data\n'

So even though there's no escape for the space character in 'special name', Python's open is smart enough to take care of the spaces and open the file correctly anyway.


> >>>>> a = "my file number"
> >>>>> a.replace(' ', '\\ ')
> >> 'my\\ file\\ number'
> >
> > What if a has more than 1 space between words? Then I think this would
> > be a safer way.
> >
> >>>> print "\\ ".join("my  file  number".split())
> > my\ file\ number
> 
> If those spaces are in the actual filename, you'll want to keep them, hence you'll need to escape those extra spaces as well.



More information about the Tutor mailing list