【问题标题】:How to check whether there is any special characters present in the given string using python? [duplicate]如何使用python检查给定字符串中是否存在任何特殊字符? [复制]
【发布时间】:2017-08-13 05:20:20
【问题描述】:

程序要求我检查给定字符串中是否存在像 !@#... 这样的特殊字符。我该怎么做?

【问题讨论】:

    标签: python


    【解决方案1】:

    首先定义一个函数。将re.search[^\w\s\d] 模式一起使用,它将匹配任何不是字母、空格、数字或下划线的内容。

    In [43]: def foo(string):
        ...:     return 'Valid' if not re.search('[^\w\s]', string) else 'Invalid'
        ...: 
    

    现在,你可以用你的字符串来调用它了:

    In [44]: foo("@#example!")
    Out[44]: 'Invalid'
    
    In [45]: foo("Seemingly valid string")
    Out[45]: 'Valid'
    

    【讨论】:

      【解决方案2】:

      试试这个any(x in string for x in '@#!')

      【讨论】:

        【解决方案3】:

        您可以使用re.match 来执行此任务。

        试试:

        word = "@#example!"
        import re
        print ("Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid")
        

        输出:

        Invalid
        

        【讨论】:

          猜你喜欢
          • 2015-11-04
          • 2021-11-21
          • 2011-07-05
          • 2014-11-25
          • 1970-01-01
          • 2020-03-15
          • 2013-06-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多