Write a program in Python to filter the elements in a series which contains a string start and endswith ‘a’



Input − Assume, you have a Series,

0    apple 1    oranges 2    alpha 3    aroma 4    beta

Output − And, the result for elements start and endswith ‘a’.

2    alpha 3    aroma

Solution 1

  • Define a Series.

  • Create regular expression to check start and endswith ‘a’

r'^[a]$|^([a]).*\1$'
  • Create an empty list and set for loop and set if condition inside to check the pattern. It is defined below,

for i in data:    if(re.search(exp, i)):       ls.append(i)
  • Finally, check the series using isin().

Example

Let us see the following implementation to get a better understanding.

import pandas as pd import re l = ["apple","oranges","alpha","aroma","beta"] data = pd.Series(l) exp = r'^[a]$|^([a]).*\1$' ls = [] for i in data:    if(re.search(exp, i)):       ls.append(i) print(data[data.isin(ls)])

Output

2 alpha 3 aroma

Solution 2

Example

import pandas as pd import re l = ["apple","oranges","alpha","aroma","beta"] data = pd.Series(l) result = list(filter(lambda x:x.startswith('a') and x.endswith('a'),l)) print(data[data.isin(result)])

Output

2 alpha 3 aroma
Updated on: 2021-02-24T06:37:41+05:30

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements