String ends with?

Instructions:

Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).

Examples:

solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false

Solution:

CodeWars当然是用Py玩啊,这是一道7kyu的水题,题目大意就是判断string是不是以ending结束。本菜鸡一开始并不知道Python有这个endswith()这个函数。

然后我的思路是先把字符串反转,判断是不是字符串string以ending开头。代码如下:

def solution(string, ending):
    # your code here...
    s = string[::-1]
    end = ending[::-1]
    if s[:len(end)] == end:
        return True
    return False

提交代码AC了之后,看到大佬们的Solutions直接调用了endswith()这个函数。5kyu的本菜鸡受教了,又学会一个新函数。

def solution(string, ending):
    return string.endswith(ending)

猜你喜欢

转载自blog.csdn.net/weixin_42449444/article/details/86372567