【发布时间】:2011-03-14 09:47:32
【问题描述】:
所以如果我的字符串是“这个家伙是个很酷的家伙”。
我想找到'dude'的第一个索引:
mystring.findfirstindex('dude') # should return 4
这个的python命令是什么?
谢谢。
【问题讨论】:
所以如果我的字符串是“这个家伙是个很酷的家伙”。
我想找到'dude'的第一个索引:
mystring.findfirstindex('dude') # should return 4
这个的python命令是什么?
谢谢。
【问题讨论】:
以算法的方式实现这一点,不使用任何 python 内置函数。 这可以实现为
def find_pos(string,word):
for i in range(len(string) - len(word)+1):
if string[i:i+len(word)] == word:
return i
return 'Not Found'
string = "the dude is a cool dude"
word = 'dude'
print(find_pos(string,word))
# output 4
【讨论】:
verse = "如果你能在所有人都在你身边时保持头脑\n正在失去他们的头脑并将其归咎于你,\n如果你能在所有人都怀疑你时相信自己,\n但也要考虑到他们的怀疑;\ n如果你可以等待而不因等待而感到疲倦,\n或被骗,不要做谎言,\n或被讨厌,不要让位于仇恨,\n但不要看起来太好,也不说话太聪明了:”
enter code here
print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))
【讨论】:
def find_pos(chaine,x):
for i in range(len(chaine)):
if chaine[i] ==x :
return 'yes',i
return 'no'
【讨论】:
index 和 find
在find 方法旁边还有index。 find 和 index 都产生相同的结果:返回第一次出现的位置,但是如果没有找到 index 将引发 ValueError 而 find 返回 -1 . Speedwise,两者都有相同的基准测试结果。
s.find(t) #returns: -1, or index where t starts in s
s.index(t) #returns: Same as find, but raises ValueError if t is not in s
rfind和rindex:一般情况下,find和index返回传入字符串开始的最小索引,
rfind和rindex返回最大索引开始的地方 大多数字符串搜索算法都是从从左到右进行搜索,所以以r开头的函数表示搜索是从从右到左进行的。
因此,如果您正在搜索的元素的可能性接近列表的末尾而不是列表的开头,rfind 或 rindex 会更快。
s.rfind(t) #returns: Same as find, but searched right to left
s.rindex(t) #returns: Same as index, but searches right to left
来源: Python:可视化快速入门指南,Toby Donaldson
【讨论】:
input_string = "this is a sentence" 并且如果我们希望找到单词 is 的第一次出现,那么它会工作吗? # first occurence of word in a sentence input_string = "this is a sentence" # return the index of the word matching_word = "is" input_string.find("is")
'this is a sentence'.find(' is ')
>>> s = "the dude is a cool dude"
>>> s.find('dude')
4
【讨论】:
-1
this is a cool dude 中找到单词 is 怎么办?我尝试了 find 方法,但它返回索引 2 而不是 5。我如何使用 find() 实现这一点?