【问题标题】:Check if the python string contains specific characters检查python字符串是否包含特定字符
【发布时间】:2019-04-25 05:39:55
【问题描述】:

我必须编写一个提示用户输入的程序,并且只有当用户输入的字符串中的每个字符都是数字('0' - '9')或前六个字母之一时才应该打印 True字母表('A' - 'F')。否则程序应该打印 False。

我不能对这个问题使用正则表达式,因为它还没有教过,我想使用基本的布尔运算。这是我到目前为止的代码,但由于 Or's,它也将 ABCH 输出为 true。我被卡住了

string = input("Please enter your string: ")

output = string.isdigit() or ('A' in string or 'B' or string or 'C' in string or 'D' in string or 'E' in string or 'F' in string)

print(output)

另外我不确定我的程序是否应该将小写字母和大写字母视为不同,这里的字符串是指一个单词还是一个句子?

【问题讨论】:

  • string 是整个对象。您应该遍历字符串中的每个元素,例如for char in string:,然后执行您的逻辑。
  • @SyntaxVoid 我使用了这个,仍然在 WEDA 上返回 true string = input("请输入您的字符串:") for char in string: if char == ("A" or "B" or " C" or "D" or "E" or "F"): alphabet_output = "True" else: alphabet_output = "False" output = string.isdigit() or alphabet_output print(output)

标签: python-3.x


【解决方案1】:

我们可以使用str.lower 方法将每个元素设为小写,因为听起来大小写对您的问题并不重要。

string = input("Please enter your string: ")
output = True # default value

for char in string: # Char will be an individual character in string
    if (not char.lower() in "abcdef") and (not char.isdigit()):
        # if the lowercase char is not in "abcdef" or is not a digit:
        output = False
        break; # Exits the for loop

print(output)

output 只会在字符串未通过任何测试时更改为 False。否则为True

【讨论】:

  • 你也可以使用内置的all()进一步简化:output = all(c.isdigit() or c.lower() in 'abcdef' for c in s)
  • @syntaxVoid:此代码对于测试用例 ABCDD 失败,它应该返回 true,但它返回 false
  • 抱歉,现在已经修复了。我在 if 语句中将or 更改为and
猜你喜欢
  • 2019-08-15
  • 2014-01-08
  • 1970-01-01
  • 2010-12-20
  • 2014-11-25
  • 2021-12-05
  • 1970-01-01
  • 2016-08-24
  • 2013-12-23
相关资源
最近更新 更多