Reputation: 2109
Is there any way available in python that I can convert decimal numbers (99.3) to (٩ ٩ .٣ )
I can convert the simple integers to eastern Arabic but the issue is with decimal.
devanagari_nums = ('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹')
number = str(numeral)
return ''.join(devanagari_nums[int(digit)] for digit in number)
Upvotes: 0
Views: 212
Reputation: 16941
There are three ways (perhaps more) to approach this. One is to use the numeric value of the input digit (for example "6"
translates to 6
) as an index into the tuple with the output digits. The difficulty with this, as you have discovered, is that a decimal point has no numeric value. You can work around this with an if
-test:
>>> numeral = 12.345
>>> number = str(numeral)
>>> number
'12.345'
>>> digits = [devanagari_nums[int(k)] if k.isdigit() else k for k in number]
>>> ''.join(digits)
'۱۲۳.۴۵'
Python programmers almost automatically reach for a dictionary when a lookup is required. So the other obvious approach is to use a dictionary instead of a tuple for your lookup table. This amounts to explicitly stating the equivalence '6' => '۶'
instead of relying on '۶'
occupying the 6th position of the tuple.
>>> devanagari_nums = {'0':'۰', '1':'۱', '2':'۲', '3':'۳', '4':'۴', '5':'۵', '6':'۶', '7':'۷', '8':'۸', '9':'۹', '.': '.'}
>>> numeral = 12.345
>>> number = str(numeral)
>>> digits = [devanagari_nums[k] for k in number ]
>>> ''.join(digits)
'۱۲۳.۴۵'
Your question equates 99.3
with ٩ ٩ .٣
but I suspect this has more to do with the SO editor's handling of RTL scripts than with what you expect, because your code implies that you expect ٩٩.٣
. If I've got that wrong, do digits.reverse()
before ''.join(digits)
.
The third way is unobvious and very far from your original approach, so I have left it to last:
>>> tx = str.maketrans('0123456789','۰۱۲۳۴۵۶۷۸۹')
>>> number.translate(tx) # number as defined in the earlier examples
'۱۲۳.۴۵'
This looks like the first way above: a positional mapping from input character to output character. And in Python 2 that was exactly what it was. But under the hood in Python 3 it is a variant of the second way, as you will quickly discover if you examine tx
:
>>> tx
{48: 1776, 49: 1777, 50: 1778, 51: 1779, 52: 1780, 53: 1781, 54: 1782, 55: 1783, 56: 1784, 57: 1785}
I suppose I don't need to explain that ord('1') == 49
and ord('۱') == 1777
.
Upvotes: 1