在Python字符串中替换字母

2 投票
5 回答
13055 浏览
提问于 2025-04-17 19:45

我正在写一个程序,用于将法语的现在时动词转换成过去时。问题是我需要替换字母,但这些字母是用户输入的,所以我必须从行的末尾开始替换字母。以下是我目前的代码,但它并没有改变字母,只是给我报错:

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"

我尝试了单词替换,但那也不行,它只是给我返回了相同的字符串。如果有人能给我一个例子,并稍微解释一下,那就太好了。:/

5 个回答

0

不好意思

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

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

2

我觉得你在使用替换功能时可能有些问题。替换的语法可以在这里找到:这里

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'

简单来说,你想要替换的内容放在前面,接着是你想用来替换的内容。

0

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

正如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

撰写回答