python - list comprehension using regex conditional -
i have list of strings. if of these strings has 4-digit year, want truncate string @ end of year. otherwise leave strings alone.
i tried using:
x in my_strings: m=re.search("\d\d\d\d\d\d",x) if m: x=x[:m.end()] i tried:
my_strings=[x[:re.search("\d\d\d\d\d\d",x).end()] if re.search("\d\d\d\d\d\d",x) x in my_strings] neither of these working.
can tell me doing wrong?
something seems work on trivial data:
>>> regex = re.compile(r'^(.*(?<=\d)\d{4}(?=\d))(.*)') >>> strings = ['foo', 'bar', 'baz', 'foo 1999', 'foo 1999 never see this', 'bar 2010 n 2015', 'bar 20156 see this'] >>> [regex.sub(r'\1', s) s in strings] ['foo', 'bar', 'baz', 'foo 1999', 'foo 1999', 'bar 2010', 'bar 20156 see this']
Comments
Post a Comment