0

I know the Python thing that if I'm using interactive interpreter and I write '\\ ' it prints '\\ ' but if if I write print '\\ ' it prints '\ '.

What I'm trying to do is (in a script called p.py):

import os
os.system('echo ' + 'string with spaces'.replace(' ', '\ '))

obviously it won't let me do this. I mean, Python manages to add TWO backslashes instead of one but I think it does so only in interactive mode, but the terminal, when passed special chars like \, ignores them.

So that, as the output of the provious code, I get:

local:$ string with spaces

and not

local:$ string\ with\ spaces 

I already tried hardcoded strings and everything else in Python, but I guess the problem is with shell strings.

How could I solve this?

It it can help to find alteratives solutions, what I'm trying to do is moving a file from python with the mv command, and this file has spaces in its name.

1
  • Just curious, why are you trying to use backslashes? The shell uses quotes note backslashes to not treat spaces as special. For example echo "string with spaces". I feel like I'm missing something here. Commented Nov 25, 2012 at 18:58

1 Answer 1

2
os.system('echo ' + 'string with spaces'.replace(' ', '\ '))

In that line, the last string '\ ' will try to escape a space, even though that is not an escape sequence. If you want it to become a space with a preceding backspace, you can either escape the backspace ('\\ '), or you can use a raw string which will ignore all escape sequences (r'\ ').

Sign up to request clarification or add additional context in comments.

Comments

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.