simplest python equivalent to R's grepl


Is there a simple/one-line python equivalent to R’s grepl function?

strings = c("aString", "yetAnotherString", "evenAnotherOne") 
grepl(pattern = "String", x =  strings) #[1]  TRUE  TRUE FALSE
Asked By: Deena



You can use list comprehension:

strings = ["aString", "yetAnotherString", "evenAnotherOne"]

["String" in i for i in strings]
#Out[76]: [True, True, False]

Or use re module:

import re

[bool("String", i)) for i in strings]
#Out[77]: [True, True, False]

Or with Pandas (R user may be interested in this library, using a dataframe “similar” structure):

import pandas as pd

#Out[78]: [True, True, False]
Answered By: Colonel Beauvel

A one-line equivalent is possible, using re:

import re

strings = ['aString', 'yetAnotherString', 'evenAnotherOne']
['String', x) for x in strings]

This won’t give you boolean values, but truthy results that are just as good.

Answered By: Konrad Rudolph

If you do not need a regular expression, but are just testing for the existence of a susbtring in a string:

["String" in x for x in strings]
Answered By: Ben
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.