如果字符串中的最后三个字符匹配条件,则替换它们

Kyl*_*den 6 python string python-3.x

我正在尝试获取用户输入的字符串,如果它以 结尾'ion',则替换该字符串的最后三个字符并添加一个'e'.

def ion2e(s):
    if s[-3:]=='ion':
        print (s[-3:]+'e')
    else:
        print (s)
Run Code Online (Sandbox Code Playgroud)

tim*_*geb 6

使用str.endswith

>>> def ion2e(s):
...     return s[:-3] + 'e' if s.endswith('ion') else s
... 
>>> ion2e('xxxion')
'xxxe'
>>> ion2e('xx')
'xx'
Run Code Online (Sandbox Code Playgroud)


Pru*_*une 2

移动打印中的冒号。您需要直到-3 个元素的字符串,而不是字符串的末尾。

def ion2e(s):
    if s[-3:]=='ion':
        print (s[:-3]+'e')
    else:
        print (s)

t = "constitution"
ion2e(t)
Run Code Online (Sandbox Code Playgroud)

另外,您熟悉单语句if表达式吗?如果您想返回值而不是打印它,您的函数可能会简化为这样。

def ion2e(s):
    return s[:-3]+'e' if s[-3:]=='ion' else s
Run Code Online (Sandbox Code Playgroud)