Slider range display string

I wish to display a string using a translation list in a ranged slider.

For instance, in the following snippet, I have a ranged slider that goes to 1 to 3, and if the value is 1, I want the slider to display “First option”. From the docs, I see that it is easy to display “Option 1” using C style formatting, but I am not sure if what I want is possible.

Code snippet:

    slider_values = [1, 2, 3]
    slider_strings = ["First option", "Second option", "Third option"]
    slider_string = st.slider(
        "String slider",
        value=(min(slider_values), max(slider_values)),

Obviously this doesn’t work and I hope someone knows the way to do it.

I don’t have a clear idea of what you are wanting to get out of the slider, so apologies if this isn’t the question.

If you want string values instead of numeric values to display, you can use st.select_slider instead of slider. You can set the initial value to a single or tuple just as before.

translate_string = ["12", "23", "34", "45", "56"]
slider_string = st.select_slider(
        "String slider",
        value=("12", "56")

Sorry I wasn’t clear enough.
I edited the initial post to add an example of what I want and why I haven’t been able to do it.

I will try to rephrase one more time to make sure this is understood better.
Would it be possible to get the value of a ranged slider and then pass it as an index to a string list to display that string ?
For example: slider_string value is 2, I get the 2nd element of the slider_strings list which is “Second option” that I then display that string instead of 2.

I think st.slider is restricted to numeric values, st.select_slider should be more general in that sense, because you can pass a formatting function (see kwarg format_func in st.select_slider - Streamlit Docs)



import streamlit as st

slider_values = [1,2,3]
slider_strings = ["First option", "Second option", "Third option"]

def stringify(i:int = 0) -> str:
    return slider_strings[i-1]

myslider = st.select_slider(
    "String slider",

st.write(f"## The value of the widgets is the number, not the string: {myslider}")

Yes, I use a select slider with strings for other pages in my app it works well. I hope the Streamlit team will upgrade the ranged slider, I find the alternatives pretty mediocre.

So, how would the upgraded ranged slider work? Like the code in the OP, and it would return a string instead of a number?

Maybe I’m still missing the point, but the select_slider can handle a range same as slider and can output numbers.

values = range(5)
labels = ['first','second','third','fourth','fifth']

selection = st.select_slider('Choose a range',values,value=(1,3), format_func=(lambda x:labels[x]))

st.write(f'The selection is {selection} with values having type {type(selection[0])}.')


1 Like

Whoops, you’re right, it is even written in the docs :man_facepalming:
Thanks, that solves the issue.