Compare for a specific string containing a substring of ranging numbers

Question:

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.

Asked By: Direct_Moonlight

||

Answers:

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.

Answered By: JeffC
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.