Search code examples
pythonunicodebraille

Trying To Create Table To Braille In Python


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.

Image Of Code Just In Case


Solution

  • \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)