Saxasianguy
Saxasianguy

Reputation: 57

Removing the square brackets, commas and single quote?

Python 3. I am trying to return the function so that It would take a single word and convert it to Cow Latin. I want to get rid of the square bracket, the comma and single apostrophes when I run my function.

My function is:

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]

when I test the function with

cow_latin = cow_latinify_sentence("Cook me some eggs")
print(cow_latin)

I get ['ookcoo', 'emoo', 'omesoo', 'eggsmoo'] but I want ookcoo emoo omesoo eggsmoo

Upvotes: 1

Views: 12784

Answers (4)

John1024
John1024

Reputation: 113834

Let's define our variables:

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

Find the cow-latin:

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

Upvotes: 0

Shashank
Shashank

Reputation: 13869

Just add an asterisk before the variable name to unpack the list and feed its elements as positional arguments to print.

print(*cow_latin)

Upvotes: 5

Álvaro Reneses
Álvaro Reneses

Reputation: 701

Use ' '.join(list) for concatenating the list elements into a string.

In your code:

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

Upvotes: 2

halex
halex

Reputation: 16403

Your function cow_latinify_sentence returns a list of strings you need to join with spaces to get your desired output:

print(" ".join(cow_latin))

Upvotes: 1

Related Questions