Kaveh P. Yousefi
Kaveh P. Yousefi

Reputation: 185

How to select a specific number of elements in a list of strings that start with a specific character in python?

I have a list containing files that starts with a date like:

["CITY_NAME_20170102", "CITY_NAME_20170103", ...]

Now, I want to run a single-line code to choose only specific years from this long list for each specific city. Only thing that comes to my mind in the first is to run a for loop and write an if clause to go over all the file names and only append the ones starting with the specific year and city. But, I'm kind of sure there is an easier way of doing this.

Is there any function that can search through all the elements and give me the one starting with the year 2017, for example?

Upvotes: 0

Views: 1699

Answers (2)

magikarp
magikarp

Reputation: 470

This is effectively the same thing as you mentioned.

L = ["CITY_NAME_20170102", "CITY_NAME_20160103"]
year = 2017

# one-line code
L_out = [elem for elem in L if year == L.split("_")[-1][0:4]]

Output: ['CITY_NAME_20170102']

Upvotes: 0

Ch3steR
Ch3steR

Reputation: 20669

To extract the year from the string given you use negative indexing.

Example:

a="CITY_NAME_20170103"
a[-8:-4]
# '2017'

Pythonic way would be

[s for s in list_of_strings if x[-8:-4] == '2017'] #Suggested by @schwobaseggl in the comments

You can also use filter to obtain the list of strings with year 2017

list(filter(lambda x: x[-8:-4]=='2017',list_of_strings))

Upvotes: 4

Related Questions