【问题标题】:How to let the input text in Streamlit only accept string not number?如何让 Streamlit 中的输入文本只接受字符串而不接受数字?
【发布时间】:2022-01-19 10:57:36
【问题描述】:

我怎样才能让 st.input_text 只接受字符串?如果用户输入数字,则会弹出一条错误消息。有人有解决办法吗?

【问题讨论】:

    标签: python streamlit


    【解决方案1】:

    isalpha( ) 是一个不错的选择。下面是一个只允许字符串作为输入的应用。

    def main():
        st.title("Only allow text example")
        
        text = str(st.text_input('Type something'))
    
        #only allow strings
        if text.isalpha():
            st.write(text, '...works as its a string', )
        else:
            st.write('Please type in a string ')
    
    
    if __name__ == "__main__":
        main()  
    
      
    

    【讨论】:

      【解决方案2】:

      这将强制输入为字符串:

      user_input = st.text_input("label goes here", default_value_goes_here)
      if user_input.isalpha():
              st.write(text, 'string', )
          else:
              st.write('Please type in a string ')
      

      【讨论】:

        【解决方案3】:

        你可以使用 ***.isalpha() #returns true if 之前的字符串。是字母。

        a = input("Enter input:")
        if not a.isalpha():
            print("Oops!  That was no valid string.  Try again...")
        
        

        【讨论】:

          猜你喜欢
          • 2014-03-26
          • 2015-10-08
          • 1970-01-01
          • 2013-12-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多