python - 在 Python 中检查字符串是大写、小写还是混合大小写

标签 python string

我想在 Python 中根据它们是大写、小写还是混合大小写来对字符串列表进行分类

我该怎么做?

最佳答案

字符串上有许多“is 方法”。 islower()isupper()应该满足您的需求:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

以下是如何使用这些方法对字符串列表进行分类的示例:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

关于python - 在 Python 中检查字符串是大写、小写还是混合大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8222855/

相关文章:

javascript - python函数可以像javascript一样在html中运行吗?

c - 如何使用带有标准输入流的 fscanf 终止 while 循环

c++ - 为什么我的 SPOJ GCD2 代码在 SPOJ 上出错?

c# - String.StartsWith 在下一个字符是素数符号时不起作用 (char)697

PHP DOM 解析器移动关闭 Div 标记

创建一个新字符串,该字符串将由其他两个字符串中的常见字母组成

Python、Numpy、多维数组相加的方法(广播)

python - 在提供的范围内只创建一个随机素数

python - 此文本在 python 中的正则表达式是什么

python - 如何使用 related_name 查询 M2M