[Tutor] Raw string
Neven Goršić
neven.gorsic at gmail.com
Mon Jul 21 10:42:35 CEST 2008
On Mon, Jul 21, 2008 at 9:44 AM, Monika Jisswel
<monjissvel at googlemail.com> wrote:
> instead of s='e:\mm tests\1. exp files\5.MOC-1012.exp'
> try to use : s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace(
> '\\', '\\\\')
> for me here is what it gives:
>
>>>> s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace('\\', '\\\\')
>>>> print s
> e:\\mm tests\\1. exp files\\5.MOC-1012.exp
>>>> s.split('\\\\')
> ['e:', 'mm tests', '1. exp files', '5.MOC-1012.exp']
>
>
> why \\ i you only have one \ ? : you need to escape it because its a
> special character to the python interpreter.
>
>
> the r character is important in the expression s = r'e:\mm tests\1. exp
> files\5.MOC-1012.exp'.replace('\\', '\\\\') because it tells the interpreter
> to take the string as RAW and thus leave it unchanged even if it contains
> special characters that should actually be treated special.
>
> now to use the r or not to use it ? when to use it ? how to use it ? I
> always use it ! & always had the result I expected, so I would suggest you
> use it always too specialy with the re module, ofcourse unless the result is
> not satisaying you,
>
> so this code (using r this time works too) :
>
>>>> s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace(r'\\', r'\\\\')
>>>> print s
> e:\\mm tests\\1. exp files\\5.MOC-1012.exp
>>>> s.split('\\\\')
> ['e:', 'mm tests', '1. exp files', '5.MOC-1012.exp']
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--------------------
Thanks,
I am aware of goodies that raw string offers, but my question was how to
use it with variable that already contains string. :)
More information about the Tutor
mailing list