string translate, replace, find and the forward slash

Arnaud Delobelle arnodel at googlemail.com
Tue Apr 29 17:46:13 EDT 2008


destroooooy <destroooooy at gmail.com> writes:

> On Apr 29, 4:50 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
>>
>> marigold:junk arno$ python
>> Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)
>> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
>> Type "help", "copyright", "credits" or "license" for more information.
>>
>> >>> unsafe_chars = "/#()[]!@$%^&*{}\'\"`?<>| \t\n"
>> >>> table = range(256)
>> >>> for c in unsafe_chars: table[ord(c)] = ord('_')
>> ...
>> >>> table = ''.join(chr(o) for o in table)
>> >>> 'Jon(&Mark/Steve)'.translate(table)
>> 'Jon__Mark_Steve_'
>>
>> --
>> Arnaud
>
>
> Okay, so that definitely works. Thanks!
>
> However, the chances of me coming up with that on my own were
> completely nonexistent, and I'd still like to know how one would use
> maketranstable() to get the same result...

Do you mean maketrans() from the string module? I didn't know about
it, but I've tried it and it works too:

>>> import string
>>> unsafe_chars = "/#()[]!@$%^&*{}\'\"`?<>| \t\n"
>>> alt_chars = "_________________________"
>>> table = string.maketrans(unsafe_chars, alt_chars)
>>> "a/b/c".translate(table)
'a_b_c'
>>>

-- 
Arnaud



More information about the Python-list mailing list