I am trying to reverse Hebrew string in Python:
JavaScript
x
4
1
line = 'אבגד'
2
reversed = line[::-1]
3
print reversed
4
but I get:
JavaScript
1
2
1
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 0: ordinal not in range(128)
2
Care to explain what I’m doing wrong?
EDIT:
I’m also trying to save the string into a file using:
JavaScript
1
3
1
w1 = open('~/fileName', 'w')
2
w1.write(reverseLine)
3
but now I get:
JavaScript
1
3
1
return codecs.charmap_encode(input,errors,encoding_table)
2
UnicodeEncodeError: 'charmap' codec can't encode characters in position 1-3: character maps to <undefined>
3
Any ideas how to fix that, too?
Advertisement
Answer
Adding u
in front of the hebrew string works for me:
JavaScript
1
7
1
In [1]: line = u'אבגד'
2
3
In [2]: reversed = line[::-1]
4
5
In [2]: print reversed
6
דגבא
7
To your second question, you can use:
JavaScript
1
5
1
import codecs
2
3
w1 = codecs.open("~/fileName", "r", "utf-8")
4
w1.write(reversed)
5
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:
JavaScript
1
3
1
with open('~/fileName', 'w') as f:
2
f.write(reversed.encode('utf-8'))
3