Skip to content Skip to sidebar Skip to footer

Replace Letters In Python String

Im writing a program for french that turns present tense verbs into past tense. The problem is that I need to replace letters but they are user inputed so I have to have it replaci

Solution 1:

IMO there might be a problem with the way you are using replace. The syntax for replace is explained. here

string.replace(s, old, new[, maxreplace])

This ipython session might be able to help you.

In [1]: mystring = "whatever"

In [2]: mystring.replace('er', 'u')
Out[2]: 'whatevu'

In [3]: mystring
Out[3]: 'whatever'

basically the pattern you want replaced comes first, followed by the string you want to replace with.

Solution 2:

String is inmutable, so u can't replace only the 2 last letters... you must create a new string from the existant.

and as said by MM-BB, replace will replace all the ocurance of the letter...

try

word = raw_input("what words do you want to turn into past tense?")
word2 = word

if word2.endswith("re"):
    word3 = word2[:-2] + 'u'print word3

elif word2.endswith("ir"):
    word3 = word2[:-2] + "i"print word3

elif word2.endswith("er"):
    word3 = word2[:-2] + "e"print word3

else:
    print"nope"

ex 1 :

what words do you want to turn into past tense?sentir
senti

ex 2 :

what words do you want to turn into past tense?manger
mange

Solution 3:

excuse me

word3 = word2.replace('u', 're')

above line code can make a false result because maybe exist another "er" in your word

Solution 4:

I think that regular expressions will be a better solution here, and the subn method in particular.

import re

word = 'sentir'for before, after in [(r're$','u'),(r'ir$','i'),(r'er$','e')]:
    changed_word, substitutions  = re.subn(before, after, word)
    if substitutions:
        print changed_word
        breakelse:
    print"nope"

Solution 5:

essentially what you've done wrong is "word2.replace('u', 're')" This means that you are replace 'u' with 're' inside the var word2. I have changed the code;

 word = raw_input("what words do you want to turn into past tense?")
 word2= word

 if word2.endswith("re"):
    word3 = word2.replace('re', 'u')
    print word3

  elif word2.endswith("ir"):
     word2[-2:] = "i"print word2

 elif word2.endswith("er"):
    word2[-2:] = "e"print word2

 else:
     print"nope"

Post a Comment for "Replace Letters In Python String"