为什么这个布尔值是假的?

2024-10-01 15:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么Python说strvowel中找不到“e”?你知道吗

我尝试将字符串格式化为: 但那也不行

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'))

打印报表应为:

esterday-yay always!"-"ay omputer-cay

它们目前是:

y-yesterdaay "-"always!ay r-computeay

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


Tags: 字符串inforifnotelementfindalways
3条回答

w是一个类似“昨天”的单词时,element是一个类似“y”的字符。当你说

v = element.find(strvowel)

你在问“y”中“'a''e''i''o''u''a''e''i''o''u'”的位置(它永远不会在那里)。你知道吗

我最好的猜测是你希望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

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

#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。你知道吗

假设变量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))

相关问题 更多 >

    热门问题