-2

I tried to replace vowels and add il to them using this code but it didnt work, help!

line=input("What do you want to say?\n")
line = line.replace('e', 'ile')
line = line.replace('o', 'ilo')
line = line.replace('a', 'ila')
line = line.replace('i', 'ili')
line = line.replace('u', 'ilu')
line = line.replace('y', 'ily')
print (line)

But if you type a long sentence it stop working correctly. could someone please help me? Want to print "Hello world" it prints: Hililellililo wililorld when should print Hilellilo Wilorld

Zeo
  • 1
  • 1

3 Answers3

1

Try replacing any occurrence of the letters you want with regex. Like this i.e:

import re

re.sub(r'[eE]', 'i$0', "Hello World")

You can replace any letter you want putting them inside the square brackets.

Additionally, that 'i$0' is the literal character 'i' and $0 the letter that was matched.

Carlos Afonso
  • 1,927
  • 1
  • 12
  • 22
0
"Hello world".replace('e', 'ie')

But your question is not very clear, may be you mean something different.

CrazyElf
  • 763
  • 2
  • 6
  • 17
0

Whenever you do multiple replacements after each other, you always need to be careful with the order in which you do them. In your case put this replacement first:

line = line.replace('i', 'ili')

Otherwise it replaces the i's in the replacements that have been done before.

When you need to do many replacements it is often better to use an approach that avoids these problems. One of them can be using regular expressions, as already proposed. Another is scanning the text from start to end for items to replace and replace each item when you find it during the scan and continue scanning after the replacement.

  • Now Im really close in what I wanted to do but right now I want to fix a problem which is when you use 2 or more vowels join together for example you(3 joined vowels) it would only use 1 "il" so it would convert from you to yilou – Zeo Jul 19 '17 at 18:05
  • Then you could work with a regular expression or by scanning the text yourself as already proposed. It will become to complicated with separate replacements. For regular expressions, just add a + sign after the square brackets (meaning 1 or more of these). I am not familiar with php, but I guess it would become re.sub(r'[aeiou]+', 'il$0', "Hello World"). – Stefan Mondelaers Jul 19 '17 at 18:20