检查Python字符串是否包含特定字符。

3

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

由于还没有学习正则表达式,我不能使用正则表达式来解决这个问题,我想使用基本的布尔运算。目前我写的代码也会将ABCH识别为True,因为使用了Or运算符。我陷入了困境。

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是指一个单词还是一个句子?


string 是一个完整的对象。你应该像 for char in string: 那样循环遍历字符串中的每个元素,然后执行你的逻辑。 - SyntaxVoid
@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) - Aayush Gupta
1个回答

2
我们可以使用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

最初的回答将只在字符串未通过任何测试时更改为False,否则将保持True。

2
你也可以使用内置的 all() 进一步简化代码:output = all(c.isdigit() or c.lower() in 'abcdef' for c in s) - benvc
@syntaxVoid:这段代码在测试用例 ABCDD 上失败了,它应该返回 true,但它返回了 false。 - Aayush Gupta
1
抱歉,现在已经修复了。我在if语句中将“or”更改为“and”。 - SyntaxVoid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接