2

我正在为法语编写一个程序,将现在时动词变成过去时。问题是我需要替换字母,但它们是用户输入的,所以我必须让它替换行尾的字母。这是我到目前为止所拥有的,但它不会改变它只是给出一个错误的字母:

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"

我尝试了单词替换,但这也不起作用,它只是给了我相同的字符串。如果有人可以给我一个例子,也许可以稍微解释一下,那就太棒了。:/

4

5 回答 5

2

IMO 您使用替换的方式可能存在问题。解释了替换的语法。这里

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'

基本上你想要替换的模式首先出现,然后是你想要替换的字符串。

于 2013-03-20T15:54:34.687 回答
0

打扰一下

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

上面的代码可能会产生错误的结果,因为
您的单词中可能存在另一个“er”

于 2013-03-20T15:57:39.510 回答
0

字符串是不可变的,所以你不能只替换最后两个字母......你必须从现有的字符串创建一个新字符串。

正如MM-BB所说,replace将替换字母的所有出现......

尝试

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
于 2013-03-20T16:06:42.797 回答
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"
于 2013-03-20T16:30:27.907 回答
0

本质上你做错的是“word2.replace('u','re')”这意味着你在var word2中用're'替换'u'。我已经更改了代码;

 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"
于 2018-03-31T07:37:50.093 回答