2010-12-08 57 views
1

好的,所以我试图从一个名为smallstr的小变量直到它结束,在str(称为bigstr)中获得距离。 例如:从str到结尾的距离(python)

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

then 
distance = 8 

我试图用重,但我这个图书馆总共小白。

回答

4

我不知道,如果你需要重新进行,继就够了:

采用分体式:

>>> 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 

你也将注意distance是9而不是8,因为它计算空格 - 'What are '

如果您担心的话,您也可以使用strip去除任何空格。

如果你还是想用重:然后使用搜索

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

+1,但他似乎想的结束从针末端的距离干草堆,不是从干草堆开始到针头开始。幸运的是,这很简单:`len(bigstr) - len(smallstr) - bigstr.index(smallstr)`。 – 2010-12-08 09:20:29

+0

这两个答案都是从字符串的开始处开始计算距离,直到字符串结束。这就是为什么你得到9而不是8。 – jchl 2010-12-08 09:21:33

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

import re 
match = re.search(smallstr, bigstr) 
distance = len(bigstr) - match.end() 
5
distance = len(bigstr) - (bigstr.index(smallstr) + len(smallstr))