如果字符串中的字母是辅音,则将字母加倍并在其之间加上“ o”,否则

时间:2018-09-10 10:00:06

标签: python string

我正在尝试解决一个问题,该问题要求我句子并把每个辅音加倍,并在两者之间加一个'o'。

我知道可以在一行中使用if语句,但是'else'语句不起作用。

vowels = list('aeiouyäöå')
consonants = list('qwrtpsdfghjklzxcvbnm')


# if letter is a consonant then double it and out 'o' in between.
def rovarspraket(sentence):
    return ''.join([letter for letter in sentence if letter in vowels else (letter + 'o' + letter)])

print(rovarspraket('hello friend'))
# should output 'hohelollolo fofrorienondod'.

2 个答案:

答案 0 :(得分:1)

在条件理解中,else-part的语法有点错误:

def rovarspraket(sentence):
    return ''.join([l if l in vowels else (l + 'o' + l) for l in sentence])

甚至更好(更健壮的wrt空格):

def rovarspraket(sentence):
    return ''.join([(l + 'o' + l) if l in consonants else l for l in sentence])

>>> print(rovarspraket('hello friend'))
hohelollolo fofrorienondod

答案 1 :(得分:0)

空间也很重要:

return ''.join(letter if letter in vowels or letter == ' ' else (letter + 'o' + letter)for letter in sentence)

整个代码:

vowels = list('aeiouyäöå')
consonants = list('qwrtpsdfghjklzxcvbnm')


# if letter is a consonant then double it and out 'o' in between.
def rovarspraket(sentence):
    return ''.join(letter if letter in vowels or letter == ' ' else (letter + 'o' + letter)for letter in sentence)

print(rovarspraket('hello friend'))

输出:

hohelollolo fofrorienondod