Replacing a space with \

Hello. I've been really struggling with this one and can't for the life of me solve it.
I have a string, let's say: Hello there and I need the space to be replaces with \ (slash space) but the problem I'm facing is that if I'm replacing with that, python will introduce another slash to escape it but I only need one slash, not two. The final result should be Hello\ there and not Hello\\ there. Can anyone enlighten me ?

Posted Mar 19, 2020, 3:10 PM UTC

111
Vhin•

Try printing it. I doubt there's actually two \.

>>> string = "hello world".replace(" ", "\\")
>>> string
'hello\\world'
>>> print(string)
hello\world
2
MeNotSantaOP•

This is what I get
https://imgur.com/a/3uX0CNo
Edit: Thanks for teaching me something new. I had no idea that if the value is not stored on a variable, there is additional escaping.

1
JohnnyJordaan•

Read carefully what he said

Try printing it

And the last statement in his code

>>> print(string)

he indicates to use print() as that prevents the addition of extra escaping slashes.

3
Vhin•

Because you're not printing it. It's falling back to string's repr, which escapes characters. Example:

>>> '\n'
'\n'
>>> print('\n')


>>>

If you're still convinced that your string is wrong and not just a display issue, try taking the len and you'll see that the second \ isn't being counted because it's not actually in the string.

3
SirBerthelot•

You've to actually write a double slash \ in order to get just one printed. If not, python will interpret it as an scape character as you're experiencing Edit: fun fact. Back there in the first line I wrote a double slash but it's only one visible

1
MeNotSantaOP•

Tried it and still get double slash
https://imgur.com/5b1BlUs

1
SirBerthelot•

Curious to say the least My trial

1
MeNotSantaOP•

I will try a different python version and see if I get different results. I'm currently running 3.8.1

1
SirBerthelot•

3.7.2 here

1
bladeoflight16•

Are you trying to escape the string for some other language/interpreter to be able to process it correctly? If so, you should look into finding an existing function that escapes strings for it instead of doing this manually.

1