Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #53909 > unrolled thread
| Started by | Peter Otten <__peter__@web.de> |
|---|---|
| First post | 2013-09-10 09:46 +0200 |
| Last post | 2013-09-10 09:46 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: a gift function and a question Peter Otten <__peter__@web.de> - 2013-09-10 09:46 +0200
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2013-09-10 09:46 +0200 |
| Subject | Re: a gift function and a question |
| Message-ID | <mailman.203.1378799217.5461.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web