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.
Answer from Anuvrat Parashar on Stack OverflowIMO 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.
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
Python: How can I replace one specific character on a string while leaving the rest of the string as it was?
Python - Replacing letters in a string? - Stack Overflow
Replace character in string
How to replace a string that is all the same character at a specific index?
word1 = input("Word: ") # lets say that the given word is "tower"
word2 = "********************"
word2 = word2.replace(word[3], word[3])
print(word2)
# Now the my code replaces all the "*" characters with the character "e"
# It just prints "eeeeeeeeeeeeeeeeeeee"
# I would like the code only to replace the 4th character with the other strings 4th
# I'd like it to print "***e****************"
strings are immutable, you need to assign it to a new variable and return that. replace() returns a new string and does not change it in place.
>>> def letter_replace(strng, letter, replace):
replace = str(replace)
for char in strng:
if char == letter.upper() or char == letter.lower():
strng = strng.replace(char, replace)
return strng # Or just do return strng.replace(char, replace)
else:
return "Sorry, the letter could not be replaced."
>>> letter_replace('abc', 'a', 'f')
'fbc'
strng.replace(char, replace)
This does the replacement, creating a new string, and then throws away the changed string because you don't assign it to a variable.
Since you're just going to return it anyway, you can simply write:
return strng.replace(char, replace)