Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #53909

Re: a gift function and a question

From Peter Otten <__peter__@web.de>
Subject Re: a gift function and a question
Date 2013-09-10 09:46 +0200
Organization None
References <1378757459.6005.55.camel@debian> <1378758025.32118.19881065.6BD771B7@webmail.messagingengine.com> <1378794379.6005.73.camel@debian>
Newsgroups comp.lang.python
Message-ID <mailman.203.1378799217.5461.python-list@python.org> (permalink)

Show all headers | View raw


Mohsen Pahlevanzadeh wrote:

> I completed my two functions, i say may be poeple can use them:
> ######################################33
> def integerToPersian(number):
>     listedPersian = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹']
>     listedEnglish = ['0','1','2','3','4','5','6','7','8','9']
>     returnList = list()
>            
>     for i in list(str(number)):
>         returnList.append(listedPersian[listedEnglish.index(i)])
> 
>     return ''.join(returnList)
> 
> def persianToInterger(persianNumber):
>     listedTmpString = list(persianNumber.decode("utf-8"))
>     returnList = list()
>     
>     for i in listedTmpString:
>         returnList.append(unicodedata.digit(i))
>         
>     return int (''.join(str(x) for x in returnList))

There is also the str.translate() method which takes a translation dict. 
Characters not in that dict will be left unaltered:

>>> persian = "۰۱۲۳۴۵۶۷۸۹"
>>> english = "0123456789"
>>> _p2e = str.maketrans(persian, english)
>>> _e2p = str.maketrans(english, persian)
>>> def persian_to_english(s): return s.translate(_p2e)
... 
>>> def english_to_persian(s): return s.translate(_e2p)
... 
>>> english_to_persian("alpha 12321 beta")
'alpha ۱۲۳۲۱ beta'
>>> persian_to_english(_)
'alpha 12321 beta'

[Advanced usage] If you prefer to get an error you can subclass dict:

>>> class NoDigitError(Exception):
...     pass
... 
>>> class StrictDict(dict):
...     def __missing__(self, key):
...             raise NoDigitError("Illegal codepoint #{}".format(key))
... 
>>> _e2p = StrictDict(str.maketrans(english, persian))
>>> english_to_persian("543")
'۵۴۳'
>>> english_to_persian("x543")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in english_to_persian
  File "<stdin>", line 3, in __missing__
__main__.NoDigitError: Illegal codepoint #120

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: a gift function and a question Peter Otten <__peter__@web.de> - 2013-09-10 09:46 +0200

csiph-web