我正在为法语写一个程序,将现在时态的动词变成过去时。问题是我需要替换字母,但他们是用户输入的,所以我必须让它替换行末尾的字母。这是我到目前为止所拥有的,但它并没有改变它只是给出错误的字母:
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"
我尝试了单词替换,这也没有用,它只是给了我相同的字符串。如果有人可以给我一个例子,也许可以解释一下那会很棒。 :/
答案 0 :(得分:2)
IMO可能存在使用替换方式的问题。解释了替换的语法。 here
string.replace(s, old, new[, maxreplace])
这个ipython会话可能会帮助你。
In [1]: mystring = "whatever"
In [2]: mystring.replace('er', 'u')
Out[2]: 'whatevu'
In [3]: mystring
Out[3]: 'whatever'
基本上你想要替换的模式首先出现,然后是你要替换的字符串。
答案 1 :(得分:0)
对不起
word3 = word2.replace('u', 're')
上面的行代码可能会产生错误的结果,因为
在你的话中可能存在另一个“呃”
答案 2 :(得分:0)
String是不可变的,所以你不能只替换最后2个字母......你必须从existant中创建一个新的字符串。
并且正如MM-BB所说,替换将取代信件的所有信息......
试
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"
前1:
what words do you want to turn into past tense?sentir
senti
前2:
what words do you want to turn into past tense?manger
mange
答案 3 :(得分:0)
我认为正则表达式在这里是更好的解决方案,特别是subn方法。
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"
答案 4 :(得分:0)
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"