ReXX Style translate() function for strings ?

Emile van Sebille emile at fenx.com
Tue Oct 30 20:19:35 EST 2001


"P Adhia" <padhia at yahoo.com> wrote in message
news:3281a460.0110301257.1a4d9a14 at posting.google.com...
> Hello,
>
> I am a newbie to python, and remain impressed with the power of the
> language overall. There are however some little features that I am
> used to in ReXX (default scripting language for mainframes) that I
> could not find in python.
>
> ReXX has a translate() function that is much more powerful (and I
> think coule be a nice addition to python; of course with a different
> name)
>
> e.g. in ReXX, to change a date from yyyymmdd to mm/dd/yyyy is
> trivially simple,
> new_date = Translate('56/78/1234', old_date, '12345678')
>
> for formal syntax refert to,
> http://users.comlab.ox.ac.uk/ian.collier/Docs/rexx_ref/F/BI
>

Easy enough to do...


""" from http://users.comlab.ox.ac.uk/ian.collier/Docs/rexx_ref/F/BI

TRANSLATE(string[,[tableo][,[tablei][,pad]]])

This function translates characters in string to other characters, or
may be used to change the order of characters in a string.
If neither translate table is specified, then the string is translated
into uppercase. Otherwise each character of string which is found in
tablei is translated into the corresponding character in tableo -
characters which are not found in tablei remain unchanged. The default
input table is XRANGE('00'x,'ff'x) and the default output table is the
null string. The output table is padded or truncated in order to make
it the same length as the input table, the default pad character being
a blank.
Examples:
   translate('abc123DEF')              == 'ABC123DEF'
   translate('abbc','&','b')           == 'a&&c'
   translate('abcdef','12','ec')       == 'ab2d1f'
   translate('abcdef','12','abcd','.') == '12..ef'
   translate('4123','abcd','1234')     == 'dabc'

"""

def translate(txt, tableo=None, tablei=None, pad=None):
    if tableo == tablei == None:
        return txt.upper()
    if pad == None:
        pad = ' '
    if len(tableo) < len(tablei):
        tableo = tableo + pad*(len(tablei)-len(tableo))
    for old, new in zip(tablei, tableo):
        txt = txt.replace(old, new)
    return txt

assert translate('abc123DEF')              == 'ABC123DEF'
assert translate('abbc','&','b')           == 'a&&c'
assert translate('abcdef','12','ec')       == 'ab2d1f'
assert translate('abcdef','12','abcd','.') == '12..ef'
assert translate('4123','abcd','1234')     == 'dabc'



--

Emile van Sebille
emile at fenx.com

---------





More information about the Python-list mailing list