当我返回 .join 方法来反转字符串时,我调用函数本身来这样做。如何在不使用内置 Python 方法(例如 reversed 方法)的情况下反转此字符串。def reverse_string_3(string): length = len(string) spaces = [' '] words = [] index_tracker = 0 while index_tracker < length: if string[index_tracker] not in spaces: beginning_of_word = index_tracker # we only want to increment when the index tracker is a letter and not spaces while index_tracker < length and string[index_tracker] not in spaces: index_tracker += 1 words.append(string[beginning_of_word:index_tracker]) index_tracker += 1 return "".join(reverse_string_3(string))
2 回答
侃侃无极
TA贡献2051条经验 获得超10个赞
def reverse_string(s):
if not s: # a base case ...
return ""
return s[-1] + reverse_string(s[:-1]) # a recursive case
尽管这些会产生可怕的示例问题,因为现实世界中的任何人都会使用reverse或s[::-1]
添加回答
举报
0/150
提交
取消