Skip to content
Advertisement

How to Reverse Hebrew String in Python?

I am trying to reverse Hebrew string in Python:

line = 'אבגד'
reversed = line[::-1]
print reversed

but I get:

UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 0: ordinal not in range(128)

Care to explain what I’m doing wrong?

EDIT:

I’m also trying to save the string into a file using:

w1 = open('~/fileName', 'w')
w1.write(reverseLine)

but now I get:

return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 1-3: character    maps to <undefined>

Any ideas how to fix that, too?

Advertisement

Answer

Adding u in front of the hebrew string works for me:

In [1]: line = u'אבגד'

In [2]: reversed = line[::-1]

In [2]: print reversed
דגבא

To your second question, you can use:

import codecs

w1 = codecs.open("~/fileName", "r", "utf-8")
w1.write(reversed)

To write unicode string to file fileName.

Alternatively, without using codecs, you will need to encode reversed string with utf-8 when writing to file:

with open('~/fileName', 'w') as f:
    f.write(reversed.encode('utf-8'))
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement