简体   繁体   中英

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' .

How do I do that using re.findall() ?

You don't need re.findall() here, at all.

Use:

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

The str.islower() method returns True if all letters in the string are lower-cased.

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:

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

re.findall is not what you want here. It was designed to work with a single string, not a list of them.

Instead, you can use filter and str.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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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