Search code examples
pythonpython-2.7psychopy

Why can I not include a "£" symbol in my psychopy.visual.TextStim?


I am currently trying to print a text stimulus using python 2.7.15 and Psychopy 1.90.2. Unfortanately the "£" symbol is causing the initialisation of visual.TextStim to throw an error:

money = 2
text_to_print = "£" + str(money)
bonus = visual.TextStim(win, text=text_to_print, pos=[0.7,-0.35], height=TEXT_STIM_HEIGHT, font="Arial", bold=True)
bonus.setColor('GoldenRod')
bonus.wrapWidth=1

The error reads:

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

I would like to know how I can incorporate a "£" symbol at the start of my text stimuli. Thank you.


Solution

  • Prefix non-ascii characters with u (for "unicode") so:

    text_to_print = u"£" + str(money)
    

    When one character is unicode, others will be too, just like when you add integers and floats - the more comprehensive data type is chosen. The above is simpler than the more verbose equivalent:

    text_to_print = "£" + str(money)  # Non-unicode; older libraries will go ahead and make it ascii
    text_to_print.decode('utf-8')  # Use this. Libraries respect this (except the csv module)
    

    From python3 and onwards (including PsychoPy3), everything is unicode by default so "special" characters should not pose a problem in PsychoPy.