Search code examples
pythonpython-3.xstringfindstring-formatting

Searching a string for a variable substring in a certain format


Imagine I'm trying to find a substring formatted as "X.X.X", in which the Xs can be any integer or character, in a string. I know that in Python I can use string.find("whatever") to find some substring within a string, but in this case, I'm looking to find anything that is in that format.

For example:

Say I have the string "Hello, my name is John and my Hotel room is 1.5.3, Paul's room is 1.5.4"

How do I go about finding "1.5.3" and "1.5.4" in this case?


Solution

  • You want to search for a pattern and not a known string, you may use regex with python package re and here method findall would fit

    You need to pass it your pattern, here \w\.\w\.\w would be ok, \w is for a letter or digit, and \. for a real point

    import re
    
    value = "Hello, my name is John and my Hotel room is 1.5.3, Paul's room is 1.5.4"
    result = re.findall("\w\.\w\.\w", value)
    print(result) # ['1.5.3', '1.5.4']