[Tutor] String replace question

Nick Raptis airscorp at otenet.gr
Wed Jul 28 15:06:01 CEST 2010


On 07/28/2010 03:41 PM, Rod wrote:
> Hello,
>
> I need to replace a period (.) in a domain name with a slash period (\.).
>
> I'm attempting to use the string replace method to do this.
>
> Example:
>
> uri = domain.com
>
> uri.replace('.', '\.')
>
> This returns 'domain\\.com'
>
>
>    
Of course it does! Try to print the value. Now the extra backslash is 
gone. Confused yet?

Well, the backslash is an escape character in Python and other languages 
too. It's used for special characters like newlines ( \n ).
But then how can you enter just a backslash by itself? Easy, escape it 
with a backslash. So \ becomes '\\'

The representation under your uri.replace() line reflects that (escaped) 
syntax.
When you're printing it though, you see the string as you meant it to.

So, nothing is wrong with your lines of code , there's only one 
backslash there, it just get's represented as two.

In fact, you should have escaped \. your self writing the line as such:
uri.replace('.', '\\.')
but since \. is not a special character, python is smart enough to not mind

Nick


More information about the Tutor mailing list