Skip to content

Instantly share code, notes, and snippets.

@dadoeyad
Last active September 6, 2019 09:40
Show Gist options
  • Save dadoeyad/6919114 to your computer and use it in GitHub Desktop.
Save dadoeyad/6919114 to your computer and use it in GitHub Desktop.
Django filter to convert Arabic numbers to Eastern Arabic numbers
# -*- 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 اياد')
@mhdismail
Copy link

That's even better.

def convert_to_eastern_arabic(value):
    arabic_num = ''
    for c in value:
        if 0 <= int(c) < 10:
            eastern_arabic_number = "\u066%s" % c
            arabic_num += eastern_arabic_number
    return arabic_num.decode('unicode_escape')

@dadoeyad
Copy link
Author

Thanks!
I updated the gist to use your way but to also leave other characters in the string if they're not numbers.

@mhdismail
Copy link

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')

@ar6io
Copy link

ar6io commented Sep 6, 2019

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