【问题标题】:python filter letters in a stringpython过滤字符串中的字母
【发布时间】:2016-01-05 23:09:19
【问题描述】:

我需要一个 python 中的命令来过滤字符串中的字母但不删除它们,例如:

string =raw_input("Enter the string:")
if string.startswith("a") and string.endswith("aaa"):
    print "String accepted"
else: print "String not accepted"
if "ba" in string:
    print "String accepted"
else :
    print "String is not accepted"

我应该添加什么来禁止字符串中除了a和b之外的其他字母

【问题讨论】:

  • @machineyearning 类型为str; string 是一个标准库模块,所以最好不要隐藏它,但这没什么大不了的。
  • @machineyearning:正如 jonrsharpe 已经说过的,这里没有隐藏内置函数
  • string 不是类,也不是“内置模块”。内置函数是您可以在 __builtins__ 中找到的名称。也许您的意思是 string 是标准库中的一个模块。

标签: python string letters


【解决方案1】:

您可以使用一个集合,将您的字符串转换为一个集合,然后检查它是否是一个只有a 和b 的集合的subset。示例 -

s = raw_input("Enter the string:")
validset = set('ab')
if set(s).issubset(validset):
    print "String accepted"
else: 
    print "String not accepted"

演示 -

>>> s = "abbba"
>>> validset = set(['a','b'])
>>> if set(s).issubset(validset):
...     print "String accepted"
... else: print "String not accepted"
... 
String accepted

>>> s = "abbbac"
>>> if set(s).issubset(validset):
...     print "String accepted"
... else: print "String not accepted"
... 
String not accepted

或者如 cmets 所示,您可以使用 set.issuperset() 代替。示例 -

s = raw_input("Enter the string:")
validset = set('ab')
if validset.issuperset(s):
    print "String accepted"
else: 
    print "String not accepted"

【讨论】:

  • 您也可以使用validset.issuperset(s)。这样您就不需要将s 转换为集合。
  • @AndreaCorbellini 所说的 - 加上 validset = set('ab') 也是一种选择
  • 是的,正确,我已将 cmets 纳入答案。谢谢
  • {'a', 'b'} 也是另一种选择(尽管set('ab') 总是更短更容易输入)
  • {'a', 'b'} 在 Python 2.6 或更低版本中无法工作,所以我使用了可以在那里工作的东西。
【解决方案2】:

您可以简单地将它们替换为空字符串并检查是否还有任何内容:

string = raw_input("Enter the string:")
if string.replace('a','').replace('b',''):
    print "String not accepted"
else:
    print "String accepted"

原字符串string不会被修改。

【讨论】:

  • 在 Python 2.x 中哪个更好string.translate(None, 'ab')
【解决方案3】:

您可以使用正则表达式来搜索要过滤的字母和组合。

^((?![abcd]).)*$ 将匹配不包含 a、b、c 或 d 的内容。

【讨论】:

    【解决方案4】:

    这是正则表达式的好用处:

    import re
    my_string = raw_input("Enter the string:")
    if re.match('^[ab]+$', my_string):
        print "String accepted"
    else :
        print "String is not accepted"
    

    这将匹配仅包含字符 a 和 b 且长度非零的字符串。如果要匹配零长度字符串,请使用* 而不是+。

    【讨论】:

      【解决方案5】:

      试试这样的。它可以让您设置多个字母、符号等

      valid_char = ['a', 'b']
      
      def validate(s):
          for char in s:
              if char not in valid_char:
                  return False
          return True
      
      if validate(input("Enter the string:")):
          print('Sting Accepted')
      else:
          print('Sting not Accepted')
      

      【讨论】:

      • 我建议使用 valid_char 的集合以获得 O(n) 复杂度。
      • 嗯,以前没用过set,上面的答案看起来确实是更好的选择
      猜你喜欢
      • 2021-03-30
      • 2013-06-14
      • 2015-07-16
      • 1970-01-01
      • 2021-12-10
      • 2018-01-31
      • 1970-01-01
      • 2020-03-08
      • 2019-04-25
      相关资源
      最近更新 更多