删除方括号,逗号和单引号?

时间:2015-04-15 05:25:12

标签: python python-3.x

Python 3.我试图返回该函数,以便它只需一个单词并将其转换为Cow Latin。我想在运行我的功能时摆脱方括号,逗号和单撇号。

我的功能是:

alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
    if word[0].lower() in alpha:
        lista = (word.lower())
        return lista[1:] + lista[0] + "oo"
    else:
        return word + "moo"

def cow_latinify_sentence(sentence):
    words = sentence.split();
    return [cow_latinify_word(word) for word in words]

当我用

测试功能时
cow_latin = cow_latinify_sentence("Cook me some eggs")
print(cow_latin)

我得到['ookcoo', 'emoo', 'omesoo', 'eggsmoo'],但我想要ookcoo emoo omesoo eggsmoo

4 个答案:

答案 0 :(得分:2)

使用' '.join(list)将列表元素连接成一个字符串。

在您的代码中:

alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
    if word[0].lower() in alpha:
        lista = (word.lower())
        return lista[1:] + lista[0] + "oo"
    else:
        return word + "moo"

def cow_latinify_sentence(sentence):
    words = sentence.split();
    return ' '.join([cow_latinify_word(word) for word in words])

答案 1 :(得分:1)

您的函数cow_latinify_sentence会返回join所需的字符串列表,其中包含空格以获得所需的输出:

print(" ".join(cow_latin))

答案 2 :(得分:1)

只需在变量名称前添加一个星号,即可解压缩列表并将其元素作为位置参数提供给print

print(*cow_latin)

答案 3 :(得分:0)

让我们定义变量:

>>> consonants = "bcdfghjklmnpqrstvwxyz"
>>> sentence = "Cook me some eggs"

找到牛拉丁语:

>>> ' '.join(word[1:] + word[0] + 'oo' if word[0] in consonants else word + 'moo' for word in sentence.lower().split())
'ookcoo emoo omesoo eggsmoo'