How to convert Hebrew in Python?

I am trying to cancel the 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) 

Help explain what I'm doing wrong?

EDIT: The answers are wonderful, thanks! I am also trying to save a string in 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 this too?

EDIT: Find a solution, see my answer below. In short, I used

 codecs.open('~/fileName', 'w', encoding='utf-8') 

instead

 open('~/fileName', 'w') 
+4
source share
6 answers

Adding u before the Hebrew string works for me:

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

For your second question, you can use:

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

To write a unicode string to fileName .

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

 with open('~/fileName', 'w') as f: f.write(reversed.encode('utf-8')) 
+7
source

You need to use the unicode string constant:

 line = u'אבגד' reversed = line[::-1] print reversed 
+2
source

you need more than flipping a line to flip hieroglyphs, due to the opposite order of numbers, etc.

Algorithms are much more complicated;

All answers on this page (by this date) will most likely bring your numbers and non-Jewish texts.

In most cases you should use

 from bidi.algorithm: import get_display print get_display(text) 
+2
source

By default, String is treated as ascii. Use u '' for unicode

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

Make sure you use unicode objects

 line = unicode('אבגד', 'utf-8') reversed = line[::-1] print reversed 
+1
source

Found a way to write to a file:

 w1 = codecs.open('~/fileName', 'w', encoding='utf-8') w1.write(reverseLine) 
0
source

Source: https://habr.com/ru/post/1435167/


All Articles