0

Suppose I have a string str='4 for 9'.The numbers in string might differ i want to obtain the left and right text of word for that is 4,9 I have tried it with split function .Is there any regular expression i can use to obtain this?

str='4 for 9'
for_exp=str.split('for')

2 Answers 2

2

With regex,

In [1]: import re

In [2]: regex = re.compile('([\s \S]*) for ([\s \S]*)')

In [3]: str='4 for 9'

In [4]: regex.match(str).groups()
Out[1]: ('4', '9')

In [5]: regex.match("44 for 54").groups()
Out[2]: ('44', '54')

In [6]: regex.match("44 advg for 54 2243").groups()
Out[3]: ('44 advg', '54 2243')

If you put a pattern in (), the regex will consider it as a group. So after a match is found, you can look at the various groups in the match using the groups() method.

It returns a tuple of size equal to the number of groups you defined in your regex.

I am matchin on \s \S on either side of for. This will match anything (all non space and space characters). If you want onyl numbers, limit the regex to \d+ instead.

Sign up to request clarification or add additional context in comments.

Comments

1

A string in Python is actually also a list of characters, so you can do this if there is only 1 digit

a = str[0]
b = str[-1]

if you wanna use regex, for 1 or more digits

number = re.search('(\d+)\sfor\s(\d+)', str)

The first element is the matched result, while number[1] and number[2] hold the start and end digit.

2 Comments

There is no guarantee that the numbers are only one digit.
thanks for the reminder, just updated regex to handle cases with more digits

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.