Black Lives Matter. Please consider donating to Black Girls Code today.

How to eliminate 'u' from before printed checklist items

Hi all, I’m trying to test a program that just displays the checkboxes that are clicked, and I realized that RadioItems have a ‘value’ attribute, whereas Checklists have a ‘values’ attribute, but I don’t think that has anything to do with it. Right now it prints the items as [u’UK’, u’Germany’] for example, when I would just want UK Germany. Thanks for any help!

Here is the code:

# -*- coding: utf-8 -*-
import dash
from dash.dependencies import Input, Output
import dash_html_components as html
import dash_core_components as dcc

app = dash.Dash()

cities = ['Greece', 'UK', 'Germany']
gases = ['O3', 'NO2']

app.layout = html.Div([

    html.Label('Checkboxes'),
    dcc.Checklist(
        id = 'loc',
        options = [
            {'label': those, 'value': those} for those in cities
        ],
        values = ['UK']
    ),
    html.Div(id='loc_display'),

    dcc.Checklist(
        id = 'gas',
        options = [
            {'label': these, 'value': these} for these in gases
        ],
        values = ['O3'],
    ),

    html.Div(id='gas_display')
])

@app.callback(
    Output('loc_display', 'children'),
    [Input('loc', 'values')]
)
def call_loc(location):
    return 'You\'re seeing measurements in {}'.format(location)


@app.callback(
    Output('gas_display', 'children'),
    [Input('gas', 'values')]
)
def text_display(gases):
    return 'You\'re seeing {} measurements'.format(gases)

if __name__ == '__main__':
    app.run_server(debug=True)

The ‘u’ indicates that the string is a unicode string (which is a feature specific to Python 2, since all strings in Python 3 are unicode). If you were to return a unicode string explicitly you would not see this. However your callback is not returning the string but a list of unicode strings, so Python has to work out how to convert the list into a string. In the case of a list it looks like str(my_list) has the same effect as repr(my_list), which gives you a representation of the data structures, including the ‘u’ for any unicode strings.

The solution is to construct the string that you want and return that. For example:

You're seeing measurements in {}'.format(' '.join(location))

Also, switching to Python 3 will definitely make life easier when dealing with unicode :slight_smile:

1 Like