Reputation: 3
I've Been Trying To Create A System Which Turns A Table Of 1's And 0's To A Braille Character But It Keeps Giving Me This Error
File "brail.py", line 16 stringToWrite=u"\u"+brail([1,1,1,0,0,0,1,1]) ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape
My Current Code Is
def brail(brailList):
if len(brailList) == 8:
brailList.reverse()
brailHelperList=[0x80,0x40,0x20,0x10,0x8,0x4,0x2,0x1]
brailNum=0x0
for num in range(len(brailList)):
if brailList[num] == 1:
brailNum+=brailHelperList[num]
stringToReturn="28"+str(hex(brailNum))[2:len(str(hex(brailNum)))]
return stringToReturn
else:
return "String Needs To Be 8 In Length"
fileWrite=open('Write.txt','w',encoding="utf-8")
stringToWrite=u"\u"+brail([1,1,1,0,0,0,1,1])
fileWrite.write(stringToWrite)
fileWrite.close()
It Works When I Do fileWrite.write(u"\u28c7")
But When I Do A Function Which Should Return That Exact Same Thing It Errors.
Upvotes: 0
Views: 738
Reputation: 3
def braille(brailleString):
brailleList = []
brailleList[:0]=brailleString
if len(brailleList) > 8:
brailleList=brailleList[0:8]
if len(brailleList) < 8:
while len(brailleList) < 8:
brailleList.append('0')
brailleList1=[
int(brailleList[0]),
int(brailleList[1]),
int(brailleList[2]),
int(brailleList[4]),
int(brailleList[5]),
int(brailleList[6]),
int(brailleList[3]),
int(brailleList[7]),
]
brailleList1.reverse()
brailleHelperList=[128,64,32,16,8,4,2,1]
brailleNum=0
for num in range(len(brailleList1)):
if brailleList1[num] == 1:
brailleNum+=brailleHelperList[num]
brailleStart = 10240
return chr(brailleStart+brailleNum)
fileWrite=open('Write.txt','w',encoding="utf-16")
fileWrite.write(braille('11111111'))
fileWrite.close()
# Think Of The Braille Functions String Like It Has A Seperator In The Middle And The 1s And 0s Are Going Vertically
Upvotes: -1
Reputation: 87134
\u
is the unicode escape sequence for Python literal strings. A 4 hex digit unicode code point is expected to follow the escape sequence. It is a syntax error if the code point is missing or is too short.
>>> '\u28c7'
'⣇'
>>> '\u'
File "<stdin>", line 1
'\u'
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape
If you are using Python 3 then the u
string prefix is not required as strings are stored as unicode internally. The u
prefix was maintained for compatibility with Python 2 code.
That's the cause of the exception, however, you don't need to construct the unicode code point like that. You can use the ord()
and chr()
functions:
from unicodedata import lookup
braille_start = ord(lookup('BRAILLE PATTERN BLANK'))
return chr(braille_start + brailNum)
Upvotes: 1
Reputation: 1442
You can rewrite
stringToWrite=u"\u"+brail([1,1,1,0,0,0,1,1])
as
stringToWrite="\\u{0}".format(brail([1, 1, 1, 0, 0, 0, 1, 1]))
All strings are unicode in Python 3, so you don't need the leading "u".
Upvotes: 0