2

I'm new to coding, and I found this exercise problem in a Python practice website. The instructions go like this:

"Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".

So I inputted this code:

def translate(string): vowels=['a','e','i','o','u'] for letter in string: if letter in vowels: print(letter) else: print(letter+'o'+letter) print(translate('this is fun')) 

and I got this:

tot hoh i sos o i sos o fof u non None 

So how do I put all these strings in one line? I've been scratching my head for so long. Please help and thank you:)

1
  • Use a variable to save them, then print it after for loop. Commented Oct 27, 2016 at 12:29

4 Answers 4

2

You can concatenate the strings iteratively. You should include a whitespace as part of the characters to exclude to avoid putting an 'o' in between whitespaces.

def translate(string): notconsonant = ['a','e','i','o','u', ' '] s = '' for letter in string: if letter in notconsonant: s += letter else: s += letter+'o'+letter return s 

Or use join with a generator expression that returns the right letter combination via a ternary operator:

def translate(string): notconsonant = {'a','e','i','o','u', ' '} return ''.join(letter if letter in notconsonant else letter+'o'+letter for letter in string) 

Note that you can speed up the lookup of letters that are not consonants if you made the list a set, as membership check for sets is relatively faster.


>>> translate('this is fun') 'tothohisos isos fofunon' 
Sign up to request clarification or add additional context in comments.

Comments

0

Just use the end parameter in print function. (I assumed that you are using python 3.x, with print being a function)

def translate(string): vowels=['a','e','i','o','u'] for letter in string: if letter in vowels: print(letter, end='') else: print(letter+'o'+letter, end='') print(translate('this is fun')) 

1 Comment

"tothohisos o isos o fofunon" - output after taking away the print from print(translate('this is fun'))
0

Try to append it in a temporary string and to print it at the end ;)

Comments

0

print get's you to a new line. Use a concatenation and a new string instead (here the new string is called result) :

def translate(string): vowels=['a','e','i','o','u'] # Use a new variable : result = '' for letter in string: if letter in vowels: result = result + letter else: result = result + letter + 'o' + letter return result print(translate('this is fun')) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.