a gift function and a question

Steven D'Aprano steve at pearwood.info
Tue Sep 10 03:01:20 EDT 2013


On Tue, 10 Sep 2013 00:40:59 +0430, Mohsen Pahlevanzadeh wrote:

> Dear all,
> 
> I have a gift for mailing list:
> 
> ////////////////////////////////
> def integerToPersian(number):
>     listedPersian = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹']
>     listedEnglish = ['0','1','2','3','4','5','6','7','8','9'] 
>     returnList = list()
>     listedTmpString = list(str(number))
>     for i in listedTmpString:
>         returnList.append(listedPersian[listedEnglish.index(i)])
>     return ''.join(returnList)
> ////////////////////////////////////
> When you call it such as : "integerToPersian(3455)" ,  it return ۳۴۵۵,
> ۳۴۵۵ is equivalent to 3455 in Persian and Arabic language.When you read
> a number such as reading from databae, and want to show in widget, this
> function is very useful.


Thank you Mohsen!


Here is a slightly more idiomatic version of the same function. This is 
written for Python 3:

def integerToPersian(number):
    """Convert positive integers to Persian.

    >>> integerToPersian(3455)
    '۳۴۵۵'

    Does not support negative numbers.
    """
    digit_map = dict(zip('0123456789', '۰۱۲۳۴۵۶۷۸۹'))
    digits = [digit_map[c] for c in str(number)]
    return ''.join(digits)


Python 2 version will be nearly the same except it needs to use the u 
prefix on the strings.



> My question is , do you have reverse of this function? persianToInteger?

The Python built-in int function already supports that:


py> int('۳۴۵۵')
3455


-- 
Steven



More information about the Python-list mailing list