我正在尝试使用用户输入的字符串,如果以'ion'
结尾,则替换该字符串的最后三个字符并添加'e'
。
def ion2e(s):
if s[-3:]=='ion':
print (s[-3:]+'e')
else:
print (s)
答案 0 :(得分:3)
使用str.endswith
:
>>> def ion2e(s):
... return s[:-3] + 'e' if s.endswith('ion') else s
...
>>> ion2e('xxxion')
'xxxe'
>>> ion2e('xx')
'xx'
答案 1 :(得分:1)
在打印件中移动冒号。你需要字符串最多 -3rd元素,而不是字符串的结尾。
def ion2e(s):
if s[-3:]=='ion':
print (s[:-3]+'e')
else:
print (s)
t = "constitution"
ion2e(t)
另外,您是否熟悉单语句 if 表达式?如果要返回值而不是打印它,您的功能可能会减少到此。
def ion2e(s):
return s[:-3]+'e' if s[-3:]=='ion' else s
答案 2 :(得分:1)
s[-3:]
说
让我从结尾向后开始3位数字,然后到最后
但你想要的是s
最后 3位数。这将是:
s[:-3]
所以你的整个代码应该是:
def ion2e(s):
if s[-3:]=='ion':
print (s[:-3]+'e')
else:
print (s)
答案 3 :(得分:1)
您可能还想使用 re
import re
print (re.sub("ion$", "e", 'station'))