Last active
September 6, 2019 09:40
-
-
Save dadoeyad/6919114 to your computer and use it in GitHub Desktop.
Django filter to convert Arabic numbers to Eastern Arabic numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django import template | |
register = template.Library() | |
@register.filter | |
def convert_to_eastern_arabic(value): | |
""" Converts an arabic numeral (ex. 5817) to Eastern Arabic (ex. ٥٨١٧) """ | |
for c in value: | |
try: | |
eastern_arabic_number = "\u066%s" % int(c) | |
value = value.replace(c, eastern_arabic_number.decode('unicode_escape')) | |
except: | |
pass | |
return value | |
# ِExample | |
# print convert_to_eastern_arabic(u'123 اياد') |
Thanks!
I updated the gist to use your way but to also leave other characters in the string if they're not numbers.
I see, but it's not efficient to decode in every iteration especially on a large number. Also, never loop and edit value, some issues might happen, better keep it on the safe side. Try this:
def convert_to_eastern_arabic(value):
arabic_num = ''
for c in value:
try:
eastern_arabic_number = "\u066%s" % int(c)
arabic_num += eastern_arabic_number
except:
arabic_num += c
return arabic_num.decode('unicode_escape')
hey guys! when i try to add this filter i see this error :
eastern_arabic_number = "\u066%s" % int(c)
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-4: truncated \uXXXX escape
any idea?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's even better.