String ends with?

  • 2019 年 11 月 8 日
  • 筆記

版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

本文鏈接:https://blog.csdn.net/weixin_42449444/article/details/86372567

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)