How do you use a regex in a list comprehension in Python?

后端 未结 2 454
情歌与酒
情歌与酒 2021-01-04 17:56

I\'m trying to locate all index positions of a string in a list of words and I want the values returned as a list. I would like to find the string if it is on its own, or if

2条回答
  •  一整个雨季
    2021-01-04 18:35

    You don't need to assign the result of match back to x. And your match should be on x rather than list.

    Also, you need to use re.search instead of re.match, since your the regex pattern '\W*myString\W*' will not match the first element. That's because test; is not matched by \W*. Actually, you only need to test for immediate following and preceding character, and not the complete string.

    So, you can rather use word boundaries around the string:

    pattern = r'\b' + re.escape(myString) + r'\b'
    indices = [i for i, x in enumerate(myList) if re.search(pattern, x)]
    

提交回复
热议问题