Python:检查最后一个字符串的函数

Python:检查最后一个字符串的函数,python,python-3.x,Python,Python 3.x,该函数接受用户的输入(字符串)。如果最后一个字符在字符串中出现多次,不管是大写还是小写,都应返回True,否则返回False。 代码有什么问题 def last_early(word): word.lower() if word.count(word[-1]) > 1: print("True") else: print("False") 这就是我所期望的: >>> last_early("happy birthd

该函数接受用户的输入(字符串)。如果最后一个字符在字符串中出现多次,不管是大写还是小写,都应返回True,否则返回False。 代码有什么问题

def last_early(word):
    word.lower()
    if word.count(word[-1]) > 1:
        print("True")
    else:
        print("False")
这就是我所期望的:

>>> last_early("happy birthday")
True
>>> last_early("best of luck")
False
>>> last_early("Wow")
True
>>> last_early("X")
False
  • 尝试:
def last_early(单词):
lower_word=word.lower()#word.lower不会改变单词本身
如果低位字计数(低位字[-1])>1:
返回真值
其他:
返回错误
  • 您可以通过运行以下命令进行测试:
def testlastpearly():
打印(“最后一次测试早期()…”,end=“”)
断言(上次提前(“生日快乐”)==True)
断言(最后一次提前(“好运”)==False)
断言(last_early(“Wow”)==True)
断言(last_early(“X”)==False)
打印(“通行证”)
testLastEarly()
  • 如果你想尝试更多的锻炼,看看吧

word.lower()
无效。字符串方法返回新的字符串对象,因为字符串是不可变的。您可能需要
word=word.lower()
无需计数:
返回单词[-1]。word[:-1]中的lower()。lower()
。如果最后一个字母出现在单词的其他地方,那么你有不止一个字母。