4

I'm trying to do a simple replacement of " " with "\s" (the literal \s, not some sort of backslash escape). This is what I think should happen:

>>> 'asdf hjkl'.replace(' ', '\s')
'asdf\shjkl'

I did this:

>>> 'asdf hjkl'.replace(' ', '\s')
'asdf\\shjkl'
>>> 'asdf hjkl'.replace(' ', '\\s')
'asdf\\shjkl'

Neither returns what I expected, and I can't for the life of me understand what's going on. What input do I have to use to get my expected output?

2 Answers 2

4

You're getting what you want. It just doesn't look that way in the REPL:

>>> 'asdf hjkl'.replace(' ', '\s')[4]
'\\'

As you can see, that's one character, not two.

Try printing it:

>>> print 'asdf hjkl'.replace(' ', '\s')
asdf\shjkl
Sign up to request clarification or add additional context in comments.

2 Comments

So when does the REPL act like this?
@arxanas: It's not so much about the REPL, the REPL just uses repr to print objects (except None) that result from the statements you enter. And a string's repr is a string literal that, when evaluated as Python expression, gives the same string.
2

The result is only displayed, try the following,

a = 'asdf hjkl'.replace(' ','\s')
print a

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.