Search code examples
pythonregexstringstring-matching

Compare for a specific string containing a substring of ranging numbers


How may I compare for a specific string containing a substring of ranging numbers in python?

Example: I have the following strings "t (1)", "t (2)" and "t (3)". They're all "t (*)" where * is always a number. In my usecase, it will always be "t " followed by a bracketed number.

I'm not sure how to essentially do:

if (string == "t (*)"):

where * is the range of numbers.

I googled variations of string comparison methods in python, but I don't know what's the right search term to use. I assume it involves regex.


Solution

  • Probably the easiest way to do this is using regex.

    import re
    
    s = "t (99)"
    match = re.search(r't \(\d+\)', s)
    if match:
      # found the string
    else:
      # did not find the string
    

    See demo on regex101.com.