【问题标题】:Python: How to check for specific characters inside a string from another string [duplicate]Python:如何从另一个字符串中检查字符串中的特定字符[重复]
【发布时间】:2018-03-13 20:26:08
【问题描述】:

我正在编写一个简单的程序,我想让用户输入一个字符串,然后我的代码将从另一个字符串中检查(字符串中不允许的)。

不允许的字符串有:

invalidChar = (@,#,£,{,[,},],:,;,",',|,\,/,?,~,`)

例如,如果用户输入“testing@3testing”,我希望代码告诉用户输入中有一个不允许的字符。

我原本以为的方式是使用:

if password[i]=="@":
  booleanCheck = True

但这必须重复多次,这会导致代码混乱。

提前致谢!

【问题讨论】:

  • 您可以为此使用一组字符,例如set("@#£{[}]:;\"'|\\/?~")`

标签: python string python-2.7 substring python-3.5


【解决方案1】:

你可以用这样的字符列表来测试一个字符:

invalidChar = ['@','#','£','{','[','}',']',':',';','"','\'','|',
               '\\','/','?','~','`']

input_string = 'testing@3testing'

# Let's define our logic in a function so that we can use it repeatedly
def contains_invalid_char(s):  # here we name our input string s
    for element in s:          # lets iterate through each char in s
        if element in invalidChar:  # If its in the set, do the block
            return True
    return False               # If we made it this far, all were False

# Then you can use the method to return a True or False, to use in a conditional or a print statement or whatever, like

if contains_invalid_char(input_string):
    print("It was a bad string")

【讨论】:

    【解决方案2】:

    创建一个包含无效字符的set,然后根据该集合检查密码中的每个字符。

    def has_invalid(password):
        invalidChar = set(['@','#','£','{','[','}',']',':',';','"','\'','|','\\','/','?','~','`'])
        return any(char in invalidChar for char in password)
    

    注意有些字符需要转义

    【讨论】:

      【解决方案3】:

      你可以这样做:

      >>> invalidChar = ('@','#')
      >>> password ="testing@3testing"
      >>> if any(ch in password for ch in invalidChar):
          booleanCheck = True
      
      >>> booleanCheck
      True
      

      【讨论】:

      • 不需要 if 语句 - 你可以做 booleanCheck = any(....)
      • 是的。你说的对。感谢@Wondercricket 的评论
      猜你喜欢
      • 2018-04-14
      • 2020-02-29
      • 2019-11-11
      • 2011-07-05
      • 2019-03-15
      • 1970-01-01
      • 2015-01-22
      • 2011-07-08
      相关资源
      最近更新 更多