36

I have the list that contains some items like:

"GFS01_06-13-2017 05-10-18-38.csv"
"Metadata_GFS01_06-13-2017 05-10-18-38.csv"

How to find the list item that start with "GFS01_"

In SQL I use query: select item from list where item like 'GFS01_%'

Russell Gallop
  • 1,631
  • 2
  • 17
  • 34
Learnings
  • 2,780
  • 9
  • 35
  • 55

3 Answers3

85

You have several options, but most obvious are:

Using list comprehension with a condition:

result = [i for i in some_list if i.startswith('GFS01_')]

Using filter (which returns iterator)

result = filter(lambda x: x.startswith('GFS01_'), some_list)
GabLeRoux
  • 16,715
  • 16
  • 63
  • 81
temasso
  • 1,104
  • 8
  • 6
  • Result will give ['GFS01_06-13-2017 05-10-18-38.csv'], how to remove/replace [' & '] – Learnings Jun 13 '17 at 09:37
  • @linus What do you mean by _remove/replace [' & ']_ ? – temasso Jun 13 '17 at 09:42
  • I want to replace " [' " and " '] " with blank from results – Learnings Jun 13 '17 at 09:45
  • @linus I don't fully understand your problem, but there should not be any other items in results apart from those started with 'GFS01_'. – temasso Jun 13 '17 at 09:50
  • (str(sourceFileName).replace("['","")).replace("']","") this is working...if you have better version please update... – Learnings Jun 13 '17 at 09:51
  • It retuns in the form of a list, if you want output in form of string do `for x in result: print x` I suggest looking up some of the basics of lists in the pythondocs – Ludisposed Jun 13 '17 at 09:54
4

You should try something like this :

[item for item in my_list if item.startswith('GFS01_')]

where "my_list" is your list of items.

RyanU
  • 128
  • 1
  • 8
1

If you really want the string output like this "GFS01_06-13-2017 05-10-18-38.csv","GFS01_xxx-xx-xx.csv", you could try this:

', '.join([item for item in myList if item.startswith('GFS01_')])

Or with quotes

', '.join(['"%s"' % item for item in myList if item.startswith('GFS01_')])

Filtering of list will gives you list again and that needs to be handled as per you requirement then.