python - Python:检查最后一个字符串的函数
问题描述
该函数接受用户的输入(字符串)。如果最后一个字符在字符串中出现多次,则它应该返回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(word):
lower_word = word.lower() # word.lower won't change word itself
if lower_word.count(lower_word[-1]) > 1:
return True
else:
return False
- 您可以通过运行进行测试:
def testLastEarly():
print("testing last_early()...",end="")
assert(last_early("happy birthday") == True)
assert(last_early("best of luck") == False)
assert(last_early("Wow") == True)
assert(last_early("X") == False)
print("pass")
testLastEarly()
- 如果您想尝试更多运动,请查看此处