如何在Python中获取字符的位置并将其存储在变量中?
我正在寻找一种将字符的位置整数存储到变量中的方法,但现在我使用的是Delphi2010中使用的一种方法,据Jupyter Notebook称,这种方法不正确 这是我的代码,到目前为止:如何在Python中获取字符的位置并将其存储在变量中?,python,string,function,variables,position,Python,String,Function,Variables,Position,我正在寻找一种将字符的位置整数存储到变量中的方法,但现在我使用的是Delphi2010中使用的一种方法,据Jupyter Notebook称,这种方法不正确 这是我的代码,到目前为止: def animal_crackers(text): for index in text: if index==' ': if text[0] == text[pos(index)+1]: return True
def animal_crackers(text):
for index in text:
if index==' ':
if text[0] == text[pos(index)+1]:
return True
else:
return False
else:
pass
目的是获取两个单词(单词+空格+单词),如果两个单词的开头字母匹配,则必须显示True,否则显示False,假设文本是包含两个单词的单行:
def animal_crackers(text):
words = text.split()
if len(words)== 1:
break # we only have one word!
# here, the .lower() is only necessary is the program is NOT case-sensitive
# if you do care about the case of the letter, remove them
if word[0].lower() == words[1][0].lower():
return True
else:
return false
要获取字符串中字母的索引(如标题所示),只需使用
str.index()
,或str.find()
,如果您不希望在找不到字母/子字符串时引发错误:
>>> text = 'seal sheep'
>>> text.index(' ')
4
但是,对于您的程序,如果要识别第一个和第二个单词,则不需要使用str.index
。相反,使用将给定文本拆分为子字符串列表:
>>> words = text.split() # With no arguments, splits words by whitespace
>>> words
['seal', 'sheep']
然后,您可以提取第一个单词的字母,并检查第二个单词是否以相同的字母开头:
# For readability, you can assign the two words into their own variables
>>> first_word, second_word = words[0], words[1]
>>> first_word[0] == second_word[0]
True
组合成一个函数,它可能如下所示:
def animal_crackers(text):
words = text.split()
first_word, second_word = words[0], words[1]
return first_word[0] == second_word[0]
您可能需要
my_string.index(character)
,例如'hello,world.index(“”)
,但似乎您希望循环项目并在文本上建立索引,为此,只需在enumerate(text)中对i,c执行操作:…
但是,这意味着您只需要word1,word2=text.split();返回word1[0]==word2[0]