Distance from str to the end (python)
Ok, so I'm trying to get the distance in a str (called bigstr), from a small other variable called smallstr until it ends. For example:
bigstr = 'What are you saying?'
smallstr = 'you'
then
distance = 8
I'm trying to use re, but I'm a total noob with this lib开发者_JAVA技巧rary.
distance = len(bigstr) - (bigstr.index(smallstr) + len(smallstr))
I am not sure if you need re for that, following should suffice:
Using split:
>>> bigstr = 'What are you saying?'
>>> smallstr = 'you'
>>> bigstr.split(smallstr)
['What are ', ' saying?']
>>> words = bigstr.split(smallstr)
>>> len(words[0])
9
>>> len(words[1])
8
Using index:
>>> bigstr.index(smallstr)
9
>>> len(bigstr) - bigstr.index(smallstr) -len(smallstr)
8
Also you will notice that distance
is 9 and not 8 because it counts spaces - 'What are '
You can alsways use strip to remove any spaces, if that concerns you.
If you still want to use re: Then use search
>>> import re
>>> pattern = re.compile(smallstr)
>>> match = pattern.search(bigstr)
>>> match.span()
(9, 12)
>>>
bigstr = 'What are you saying?'
smallstr = 'you'
import re
match = re.search(smallstr, bigstr)
distance = len(bigstr) - match.end()
精彩评论