Carlos
3/21/2005 11:29:00 AM
[Tom Counsell <tamc2@cam.ac.uk>, 2005-03-21 11.43 CET]
> Hello
>
> I'm a little confused and would appreciate your help. I would like to
> remove any \ characters from a string as well as some other characters.
>
> 'b\\c['.tr('\\','') # => 'bc', which is great.
>
> 'b\\c'.tr('\\c','.') # => 'b\\' which is not great.
>
> Why does adding extra characters to the tr function stop the removal of
> \ characters?
There are two levels of escaping involved here:
First, in the literal string, you use a \ to escape the \. The method
receives the string \c.
But the method also uses \ to escape (the "^" and the "-":
"555-7819".tr("1\\-9", "") => "55578").
So you must escape the \ with another \. In your string literal you must
write four \'s.
'b\\c'.tr('\\\\c','.') => "b.."
Hope this helps.