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

idjaw
  • 25,487
  • 7
  • 64
  • 83

4 Answers4

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'
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
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'))
Nf4r
  • 1,390
  • 1
  • 7
  • 9
  • 1
    "tothohisos o isos o fofunon" - output after taking away the `print` from `print(translate('this is fun'))` – Nf4r Oct 27 '16 at 12:32
0

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

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'))
Hakro
  • 2,625
  • 1
  • 12
  • 23