if else语句,用于查找字符串中字符的索引

时间:2016-09-17 19:45:08

标签: python string python-3.x indexing character

由于某些原因没有else语句,代码会找到字符串中字符的索引。但是,当我添加else语句来声明是否找不到某个字符时。即使字符在字符串中,它所做的就是给我else语句。

#Function takes a character and a string and returns the index of the character
#found in the string.
def whereIsItS(letter, word):
    #Start finding the index of characters in the string starting at 0.
    letInWord = 0
    #For loop to find specific characters in a string.
    for l in word:
        #If the letter is found it returns the index of the letter.
        if l == letter:
        #Moves to the next character in the string.
            letInWord += 1
        else:
            return "It is not there."
    #Returns the index of the character found the string.        
    return word.index(letter)

我似乎无法在没有else语句的情况下找出原因,但不能使用else语句。

4 个答案:

答案 0 :(得分:1)

这是有问题的代码:

def return_path(arr, value, path=[])
  ndx = arr.index(value)
  return path + [ndx] unless ndx.nil?
  arr.each_with_index do |o,i|
    next unless o.is_a?(Hash)
    o.each do |k,v|
      next unless v.is_a?(Array)
      path = return_path(v, value, path+[i,k])
      return path unless path.nil?
    end
  end
  nil
end

value = :stage

arr = [{ :users=>[{ :admins=>[:address, :stage] }] }]    
return_path(arr, :stage)
  #=> [0, :users, 0, :admins, 1] 

arr = [{ :users=>[{ :admins=>[:what, { :huh => [:stage, :address] }] }] }]
return_path(arr, :stage)
  #=> [0, :users, 0, :admins, 1, :huh, 0]

arr = [{ :users=>[{ :admins=>[{ :huh => [:name, :address] }, :what ] }] }]
return_path(arr, :stage)
  #=> nil 

如您所见,for l in word: #If the letter is found it returns the index of the letter. if l == letter: #Moves to the next character in the string. letInWord += 1 else: # You end the loop here # return "It is not there." # try this: print("It is not there.") 退出循环中间的函数。如果您不想离开for循环,则应使用return

请注意,您可以使用print()并且不需要整个for循环:

word.index(letter)

答案 1 :(得分:1)

return将始终退出函数,而不是继续执行任何循环。

您要么print它不在那里,但这甚至都不是真的,因为您正在打印当前的信件。

通过以下方式实现这一目标相对简单:

def whereIsItS(letter, word):
    if letter in word:
        return word.index(letter)
    else:
        return "Letter {0} not in word {1}".format(letter, word)

如果字母在单词中,则返回其索引,否则返回指定未找到的消息。

进一步用条件表达式修剪:

def whereIsItS(letter, word):
    return word.index(letter) if letter in word else "Letter {0} not in word {1}".format(letter, word)

答案 2 :(得分:0)

您正在以integerList = repeat 1条件返回功能。 将else更改为return "It is not there."

答案 3 :(得分:0)

您的错误已由我和我解释。其他人的答案。

现在让我们避免使用无效的代码。以下是3种有效的方法 (仍然是

  1. 使用enumerate获取索引和值。第一次出现:您可以返回索引
  2. 代码:

    def whereIsItS(letter, word):
        #Start finding the index of characters in the string starting at 0.
        #For loop to find specific characters in a string.
        for i,l in enumerate(word):
            #If the letter is found it returns the index of the letter.
            if l == letter:
                return i
        return "It is not there."
    
    1. 尝试index并捕获异常(似乎您的预检是为了避免此异常)
    2. 代码:

      def whereIsItS(letter, word):
          try:
              return word.index(letter)
          except ValueError:
              return "It is not there."
      
      1. 使用str.find。它查找子字符串,因此它也可以查找唯一的字母(与index不同,它不会抛出异常但只返回-1
      2. 代码:

        def whereIsItS(letter, word):
            idx = word.find(letter)
            if idx>=0:
                return idx
            else:
                return "It is not there."
        

        当然,字母不在这里的返回值实际上是不切实际的。我会选择-1(例如find)或None