user5324426 user5324426 - 3 months ago 8
Python Question

Test if a string contain a combination of a known string and unknown number in python

If I have a string for example line= "hello world 2" and the number 2 can be any number so line could be "hello world 4" is there a way to test that using in operand, I am thinking of something like that

if "world %n" in line

but that is not correct syntax

Answer
import re

if re.search("world \d", line):
   ...

This uses a quick, simple regular expression to check the line contains the word 'world' followed by a space followed by any number.

Comments