好的,所以我試圖從一個名爲smallstr的小變量直到它結束,在str(稱爲bigstr)中獲得距離。 例如:從str到結尾的距離(python)
bigstr = 'What are you saying?'
smallstr = 'you'
then
distance = 8
我試圖用重,但我這個圖書館總共小白。
好的,所以我試圖從一個名爲smallstr的小變量直到它結束,在str(稱爲bigstr)中獲得距離。 例如:從str到結尾的距離(python)
bigstr = 'What are you saying?'
smallstr = 'you'
then
distance = 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
你也將注意distance
是9而不是8,因爲它計算空格 - 'What are '
如果您擔心的話,您也可以使用strip去除任何空格。
如果你還是想用重:然後使用搜索
>>> 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()
distance = len(bigstr) - (bigstr.index(smallstr) + len(smallstr))
+1,但他似乎想的結束從針末端的距離乾草堆,不是從乾草堆開始到針頭開始。幸運的是,這很簡單:`len(bigstr) - len(smallstr) - bigstr.index(smallstr)`。 – 2010-12-08 09:20:29
這兩個答案都是從字符串的開始處開始計算距離,直到字符串結束。這就是爲什麼你得到9而不是8。 – jchl 2010-12-08 09:21:33