Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 626
Deena Avatar asked Aug 03 '16 13:08

Deena


People also ask

What is grepl R?

The grepl R function searches for matches of certain character pattern in a vector of character strings and returns a logical vector indicating which elements of the vector contained a match.

What does grep1 do in R?

The grep() is a built-in function in R. It searches for matches for certain character patterns within a character vector.


3 Answers

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(re.search("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

pd.Series(strings).str.contains('String').tolist()
#Out[78]: [True, True, False]
like image 141
Colonel Beauvel Avatar answered Oct 24 '22 06:10

Colonel Beauvel


A one-line equivalent is possible, using re:

import re

strings = ['aString', 'yetAnotherString', 'evenAnotherOne']
[re.search('String', x) for x in strings]

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

like image 33
Konrad Rudolph Avatar answered Oct 24 '22 06:10

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]
like image 2
Ben Avatar answered Oct 24 '22 05:10

Ben