简体   繁体   English

如何在Python中使用re.findall仅获取具有小写字母的字符串

[英]How to use re.findall to get only strings with lowercase letters in python

Suppose if my list has ["Apple","ball","caT","dog"] then it should give me result 'ball and 'dog' . 假设我的清单中有["Apple","ball","caT","dog"]则应该给我结果'ball ["Apple","ball","caT","dog"] 'dog'

How do I do that using re.findall() ? 我该如何使用re.findall()

You don't need re.findall() here, at all. 您根本不需要在这里re.findall()

Use: 采用:

[s for s in inputlist if s.islower()]

The str.islower() method returns True if all letters in the string are lower-cased. 如果字符串中的所有字母均为小写,则str.islower()方法返回True

Demo: 演示:

>>> inputlist = ["Apple","ball","caT","dog"]
>>> [s for s in inputlist if s.islower()]
['ball', 'dog']

Use re.findall() to find lowercased text in a larger string, not in a list: 使用re.findall()较大的字符串而不是列表中查找小写字母的文本:

>>> import re
>>> re.findall(r'\b[a-z]+\b', 'The quick Brown Fox jumped!')
['quick', 'jumped']

re.findall is not what you want here. re.findall不是您想要的。 It was designed to work with a single string, not a list of them. 它被设计为使用单个字符串,而不是它们的列表。

Instead, you can use filter and str.islower : 相反,您可以使用filterstr.islower

>>> lst = ["Apple", "ball", "caT", "dog"]
>>> # list(filter(str.islower, lst))  if you are on Python 3.x.
>>> filter(str.islower, lst)
['ball', 'dog']
>>>

Ask how to kill a mosquito with a cannon, I guess you can technically do that... 问问如何用大炮杀死蚊子,我想您可以做到这一点...

c = re.compile(r'[a-z]')

[x for x in li if len(re.findall(c,x)) == len(x)]
Out[29]: ['ball', 'dog']

(don't use regex for this) (请勿为此使用正则表达式)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM