且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查字符串是否只包含 Python 中的某些字母

更新时间:2023-02-26 13:14:01

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):