0

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?

1
  • 1
    The keyword is regex. Search for it, and I'm sure you will be able to do it easily. Commented Jun 21, 2020 at 11:19

1 Answer 1

1

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']
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that's exactly what I'm looking for. Just to clear some things up, imagine that in the last section the format has two digits, say like "X.X.XX", would that still be the same?
@Hasake \w would fit for one only, you can do \w+ for '1 or more' or \w{1,2} for "1 or 2"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.