检查字符串是否只包含 Python 中的某些字母 [英] checking if string only contains certain letters in Python

查看:29
本文介绍了检查字符串是否只包含 Python 中的某些字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个完成 MU 游戏的程序https://en.wikipedia.org/wiki/MU_puzzle

i'm trying to write a program that completes the MU game https://en.wikipedia.org/wiki/MU_puzzle

基本上我坚持确保用户输入只包含 M、U 和 I 字符.

basically i'm stuck with ensuring that the user input contains ONLY M, U and I characters.

我已经写了

alphabet = ('abcdefghijklmnopqrstuvwxyz')

string = input("Enter a combination of M, U and I: ")

if "M" and "U" and "I" in string:
    print("This is correct")
else:
    print("This is invalid")

我刚刚意识到这行不通,因为它不仅限于 M U 和 I.谁能帮我一把?

i only just realised this doesnt work because its not exclusive to just M U and I. can anyone give me a hand?

推荐答案

if all(c in "MIU" for c in string):

检查字符串的每个字符是否都是 M、I 或 U 之一.

Checks to see if every character of the string is one of M, I, or U.

请注意,这接受一个空字符串,因为它的每个字符都是 M、I 或 U,每个字符"中没有任何字符.如果您要求字符串实际包含文本,请尝试:

Note that this accepts an empty string, since every character of it is either an M, I, or a U, there just aren't any characters in "every character." If you require that the string actually contain text, try:

if string and all(c in "MIU" for c in string):

这篇关于检查字符串是否只包含 Python 中的某些字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆