Only allow the data type str for the st.text_input widget

I saw a question on StackOverflow that I wanted to answer and I stumbled upon following problem.

Suppose you want to restrict the user input from the st.text_input widget. E.g. the user can only type in strings. How would you do that?

My attempt:

import streamlit as st

def main():
    st.title("Only allow text example")
    
    #only allow strings
    text = st.text_input('Type something', value=str)

    #conditional statement to check if the input is a string
    if type(text) == str:
        st.write(text + ' ' + ' ...works as its a string')

    else:
        type(text) != str
        st.write("Please enter a string")
    

if __name__ == "__main__":
    main()

If I type in 1234 as the input it outputs …1234… works as its a string.

I read the documentation for this widget

docs for st.input_text β†’ st.text_input - Streamlit Docs

…and I know the type argument is good for hiding the text input but I don’t know what the value argument is doing. I feel like by default all that you type into the widget is a string.

Wrapping everything up into a str() is also not advisable.

text = str(st.text_input('Type something', value=str))

Okay I found a solution.

text.isaplha( ) works to check for the input.

import streamlit as st

def main():
    st.title("Only allow text example")
    
    #only allow strings
    text = str(st.text_input('Type something'))

    #conditional statement to check if the input is a string
    if text.isalpha():
        st.write(text, '...works as its a string', )
    else:
        st.write('Please type in a string ')

   
if __name__ == "__main__":
    main()

So a mixture of strings and integers doesn’t work for the input any more …

Input: 123abc
Output: Please, enter a string

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.