Python - match a word in a string with a list of strings

后端 未结 6 2193
北恋
北恋 2021-01-25 22:20

I\'m new to python and I was wondering how string comparison is done

Let\'s say I have a list of strings containing state names like

states = [\"New York         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-25 22:38

    Here's another alternative answer using a regexp:

    import re
    
    states = ["New York", "California", "Nebraska", "Idaho"]
    pattern = re.compile(r'.*(' + r'|'.join(states) + ').*')
    
    postal_addr = "1234 1st E St San Jose California 95112"
    match = pattern.match(postal_addr)
    
    if match:
        state = match.group(1)
    

提交回复
热议问题