如何获得字符在Python中的位置并将其存储在变量中?

问题描述

我正在寻找一种将字符的位置整数存储到变量中的方法,但是现在我正在使用一种在Delphi 2010中使用的方法,根据Jupyter Notebook的说法,这是不正确的

这是我到目前为止的代码

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

解决方法

要获取字符串中字母的索引(标题要求),请使用str.index()str.find(),如果您不想在字母/子字符串出现错误的情况下使用找不到:

>>> text = 'seal sheep'
>>> text.index(' ')
4

但是对于您的程序,如果要标识第一个和第二个单词,则无需使用str.index。而是使用str.split()将给定的文本分成子字符串列表:

>>> 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,words[1]

    return first_word[0] == second_word[0]
,

假定文本是包含两个单词的一行:

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