从str到端点的距离(python)

从str到端点的距离(python),python,Python,好的,我试图得到str(称为bigstr)中的距离,从另一个称为smallstr的小变量到它结束的距离。 例如: bigstr = 'What are you saying?' smallstr = 'you' then distance = 8 我正在尝试使用re,但我完全不了解这个库。我不确定您是否需要re,以下内容就足够了: 使用拆分: >>> bigstr = 'What are you saying?' >>> smallstr = 'you'

好的,我试图得到str(称为bigstr)中的距离,从另一个称为smallstr的小变量到它结束的距离。 例如:

bigstr = 'What are you saying?'
smallstr = 'you'

then
distance = 8

我正在尝试使用re,但我完全不了解这个库。

我不确定您是否需要re,以下内容就足够了:

使用拆分:

>>> 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
>>> bigstr.index(smallstr)
9
>>> len(bigstr) - bigstr.index(smallstr) -len(smallstr)
8
使用索引:

>>> 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
>>> bigstr.index(smallstr)
9
>>> len(bigstr) - bigstr.index(smallstr) -len(smallstr)
8
您还将注意到距离是9而不是8,因为它计算空格-
“是什么”

如果您需要,也可以使用strip删除任何空格

如果仍要使用re:则使用搜索

>>> import re
>>> pattern = re.compile(smallstr)
>>> match = pattern.search(bigstr)       
>>> match.span()
(9, 12)
>>> 

我不确定您是否需要re,以下内容就足够了:

使用拆分:

>>> 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
>>> bigstr.index(smallstr)
9
>>> len(bigstr) - bigstr.index(smallstr) -len(smallstr)
8
使用索引:

>>> 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
>>> bigstr.index(smallstr)
9
>>> len(bigstr) - bigstr.index(smallstr) -len(smallstr)
8
您还将注意到距离是9而不是8,因为它计算空格-
“是什么”

如果您需要,也可以使用strip删除任何空格

如果仍要使用re:则使用搜索

>>> import re
>>> pattern = re.compile(smallstr)
>>> match = pattern.search(bigstr)       
>>> match.span()
(9, 12)
>>> 

+1,但是他似乎想要从针的末端到干草堆的末端的距离,而不是从干草堆的开始到针的开始的距离。幸运的是,这很简单:
len(bigstr)-len(smallstr)-bigstr.index(smallstr)
。这就是为什么你得到的是9而不是8。@jchl@karlknechtel:非常感谢,我误解了距离部分。我已经添加了修改。我选择了这个,因为它是最完整的一个,但是@jchi reply也很有用。谢谢:D+1,但他似乎想要从针的末端到干草堆的末端的距离,而不是从干草堆的开始到针的开始的距离。幸运的是,这很简单:
len(bigstr)-len(smallstr)-bigstr.index(smallstr)
。这就是为什么你得到的是9而不是8。@jchl@karlknechtel:非常感谢,我误解了距离部分。我已经添加了修改。我选择了这个,因为它是最完整的一个,但是@jchi reply也很有用。谢谢:D