【问题标题】:Check if string is upper, lower, or mixed case in Python在 Python 中检查字符串是大写、小写还是混合大小写
【发布时间】:2012-01-03 14:29:28
【问题描述】:

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

我该怎么做?

【问题讨论】:

  • 考虑 (1) 不是字母的字符和 (2) 根本没有大小写的字母的可能性。

标签: python string


【解决方案1】:

字符串上有许多“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']

【讨论】:

  • 嗨。感谢您的简短回答。但是如何对大写的单词进行分类呢?例如:“混合词”。似乎第三个示例适合所有可能的混合词组合,例如:“mIxEd WoRD”..
  • 'hello'.istitle()
  • @Stephen 重要的是要注意istitle() 只会评估字符串是否是标题大小写,不是是否是混合大小写。对于 'The quick Brown Fox' 这样的字符串,它将返回 false,因为这不是标题大小写(但显然是混合大小写)。
【解决方案2】:

我想为此使用re 模块大喊大叫。特别是在区分大小写的情况下。

我们在编译正则表达式时使用选项re.IGNORECASE,以便在具有大量数据的生产环境中使用。

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

但是请尝试始终使用in 运算符进行字符串比较,如本文所述

faster-operation-re-match-or-str

在开始学习 python 的最佳书籍之一中也有详细介绍

idiomatic-python

【讨论】:

    猜你喜欢
    • 2018-06-17
    • 2015-04-23
    • 2020-10-21
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 2011-09-15
    • 1970-01-01
    相关资源
    最近更新 更多