[Tutor] String replace question

2010-07-28 Thread Rod
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'

Is there a way to do this so there is not a double slash before the period?

Thanks for any help,
Rod
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String replace question

2010-07-28 Thread Rod
 Try
 print uri.replace('.', '\.')
 and you'll find the replacement works fine.

 Or write the output to file, and look at the file.

 Python shows a representation on its prompt, and thus needs to escape the 
 backslash (by prepending another backslash). Otherwise you might think '\.' 
 was meant, which is simply a '.'.
 But consider:
 uri.replace('.', '\n')
 'domain\ncom'
 print uri.replace('.', '\n')
 domain
 com

 because '\n' is really a different string (character) than a backslash + 'n'.


Thanks, that was very helpful. I was using the interactive interpreter
to test things.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String replace question

2010-07-28 Thread Nick Raptis

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
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor