【问题标题】:Why is this Boolean false?为什么这个布尔值是假的?
【发布时间】:2019-10-26 02:35:48
【问题描述】:

为什么 Python 说在 strvowel 中找不到 'e'?

我尝试将字符串格式化为: 'aeiouAEIOU' 但这也不起作用

vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
strvowel = "'a' 'e' 'i' 'o' 'u' 'A' 'E' 'I' 'O' 'U'"

 if w[0] not in vowel:
        PLw = []
        for element in w:
            v = element.find(strvowel)
        PLw.append(w[v:] + '-' + w[0:v] + 'ay')
        return PLw[0]
if __name__ == '__main__':
#     encrypt(w)
#     decrypt(w)
    print(encrypt('yesterday'))
    print(encrypt('"always!"'))
    print(encrypt('computer'))

打印语句应该是:

昨天-耶 永远!”-“啊 电脑岛

他们目前是:

y-昨天 “-”总是!好吧 r-computeay

当输入单词 (w) 时,它应该找到第一个出现的元音: 前任。 “昨天”将是“e” 但它对每个字符(甚至元音)都调用 false

【问题讨论】:

  • 如果我们不知道w 是什么,我们将无法帮助您。
  • w 是任何单词。如果你看下面的代码块就会解释
  • 'y'.find(strvowel) = -1,然后将其传递给索引ww[-1:] = yfind 返回在切片 s[start:end] 中找到子字符串 sub 的字符串中的最低索引。可选参数 start 和 end 被解释为切片表示法。 如果未找到 sub,则返回 -1.
  • 它应该遍历 w 中的每个字母,直到找到元音(在本例中为 'e'),但每次迭代产生 -1 表示不存在元音。我只是想知道如何调试以便捕捉元音
  • 它的工作方式类似于'find'.find('i') 返回1

标签: python string list loops iteration


【解决方案1】:

假设变量 w 在您的示例中是单词 yesterday,搜索它的好方法是定义一个函数并返回第一次出现。

vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
w = "yesterday"
def find_first_vowel(string):
    for char in string:
        if char in vowel:
            return char

print(find_first_vowel(w))

【讨论】:

    【解决方案2】:

    w 是像“昨天”这样的词时,element 是像“y”这样的字符。当你说

    v = element.find(strvowel)
    

    你在询问“'a' 'e' 'i' 'o' 'u' 'A' 'E' 'I' 'O' 'U'” 在“y”中的位置(它可以永远不在那里)。

    我最好的猜测是您希望v 成为第一个元音的索引。您已经创建了一种检查字符是否为元音的正确方法:

    if w[0] not in vowel:
    

    所以删除 strvowel 并重新使用它:

    v = -1  # TODO: think about what happens when there are no vowels
    
    for i, letter in enumerate(w):
        if letter in vowel:
            v = i
            break
    

    【讨论】:

      【解决方案3】:

      所以你只想找到第一个元音? 这就是正则表达式的用途。

      #python standard regular expression library
      >>>import re
      
      #prepare your vowels. this means "any of those letters"
      >>> vowels = re.compile("[aeiouyAEIOUY]")
      
      #find the match. returns a Match Object. often used as a `if vowels.match(string)` too
      >>> vowels.match("yesterday")
      <re.Match object; span=(0, 1), match='y'>
      >>> match = vowels.match("yesterday")
      #  look as the object for fun
      >>> match
      <re.Match object; span=(0, 1), match='y'>
      
      #find the result
      >>> match[0]
      'y'
      # or this way
      >>> match.group()
      'y'
      

      所以要在找到的第一个元音后面加上“-ay”,你只需要这样做

      def append_yay(string):
          match = vowels.match(str)
          if match:
              return match.group() + "ay"
      
      
      append_yay("yesterday")
      

      你会得到你的-yay

      【讨论】:

        猜你喜欢
        • 2021-12-28
        • 1970-01-01
        • 2011-01-29
        • 1970-01-01
        • 1970-01-01
        • 2017-09-17
        • 1970-01-01
        • 1970-01-01
        • 2013-02-01
        相关资源
        最近更新 更多