-4

My list is ['text1', 'text2', 'text3'] so one so.

How can I extract only text1 or text2?

Tried with re but can't figure out how to do that.

Employee
  • 2,841
  • 3
  • 25
  • 48
  • Hi there welcome to SO. Your question is unclear: Why do "text1" and "text2" qualify for extraction? What have you tried with `re` (include what you've tried)? Please [edit](https://stackoverflow.com/posts/54251399/edit) your question with these details. Thanks. :-) – TrebledJ Jan 18 '19 at 09:54
  • you can certainly extract using re - regular expression. see the answer below. – MEdwin Jan 18 '19 at 10:01
  • 1
    @Satheesh two answers have been provided to your question. Please take your time to see which best works for you and mark it as accepted. – Employee Jan 18 '19 at 10:05

3 Answers3

0

Given a list

my_list = ["a", "b", "c"]

You can access the elements in the list by specifying their index between square brackets

my_list[0] # "a"
my_list[1] # "b"
my_list[2] # "c"
Employee
  • 2,841
  • 3
  • 25
  • 48
0

you can filter by using the filter function with regular expression. Like this:

import re

mylist =  ['text1', 'text2', 'text3'] 
r = re.compile("text2")
newlist = list(filter(r.match, mylist)) 
print(newlist)

result here:

['text2']
MEdwin
  • 2,755
  • 1
  • 12
  • 26
0
list_with_items = ["item1", "item2", "item3", "item4"]

list_with_search_items = ["item2", "item3"]

for item in list_with_search_items:
    if item in list_with_items:
        print(item)

output:

item2
item3

Its a simple list approach. If your list_with_items and list_with_search_items have the same length, then you can use the set approach as here: How can I compare two lists in python and return matches

madik_atma
  • 749
  • 8
  • 26