str1 = "If you're reading this half sentence you are amazing because it's half."
我不想要整个字符串的长度。我需要长度,直到它到达这个词,因为。它应该给我长度: -
“如果你正在阅读这半句话,那就太棒了”
答案 0 :(得分:2)
使用str.find
。
示例:
>>> str1 = "If you reading this half sentence you are amazing because it's half."
>>> print(str1.find('because'))
50
答案 1 :(得分:0)
你可以使用另一个函数str.index(),它做同样的事情。 find()和index()之间的唯一区别是find()方法返回-1,如果它没有找到子字符串但index()方法引发异常。 用法: len = str1.index('因为')
答案 2 :(得分:0)
你可以这样做,你必须包括空格吗?
def find_till_word(sentence, word):
count = 0
for char in sentence[:sentence.index(word)]:
count += 1
return count
输出:
>>> str1 = "If you reading this half sentence you are amazing because it's half."
>>> print(find_till_word(str1, "because"))
50