Before you close this, please try to understand the question - it's a bit different, but looks like a lot of downvoted questions.
I'm looking for a simple way to check if any substrings of a string is in a list of strings. The input is like 2018_JAN_BGD
, and I want to convert the month info in this to a (year-)quarter info. For example Q1 would be January, February and March. So I'm looking for a way to check if any of the substrings in 2018_JAN_BGD
contains JAN
, FEB
or MAR
. I could do this by writing 12 (for the whole year) if-else clauses with or's, but I feel like there's a more elegant solution in Python. I'm trying:
def tellQuarter(month):
Q1 = ('JAN','FEB','MAR')
Q2 = ('APR','MAY','JUN')
Q3 = ('JUL','AUG','SEP')
Q4 = ('OCT','NOV','DEC')
if any(for mon in Q1 in month):
return ("Q1")
if any(for mon in Q2 in month):
return ("Q2")
This is of course incorrect (invalid syntax), but I can't figure out how to put this correctly. Basically, I want to loop through Q1
, and check if any of the strings is a substring of month
.
I mean I can do
for mon in Q1:
if mon in month:
return "Q1"
but isn't there a more elegant, single-line solution to this?