Reputation: 41
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 replacing the letters from the end of the line. Here's what I have so far, but it doesn't change the letters it just gives an error:
word = raw_input("what words do you want to turn into past tense?")
word2= word
if word2.endswith("re"):
word3 = word2.replace('u', 're')
print word3
elif word2.endswith("ir"):
word2[-2:] = "i"
print word2
elif word2.endswith("er"):
word2[-2:] = "e"
print word2
else:
print "nope"
I tried word replace and that doesn't work either, it just gives me back the same string. If some one could just give me an example and maybe explain it a little that would be awesome. :/
Upvotes: 2
Views: 15696
Reputation: 21
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"
Upvotes: 0
Reputation: 2752
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
break
else:
print "nope"
Upvotes: 0
Reputation: 651
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
Upvotes: 0
Reputation: 1407
excuse me
word3 = word2.replace('u', 're')
above line code can make a false result because
maybe exist another "er" in your word
Upvotes: 0
Reputation: 3120
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.
Upvotes: 2