推荐方法,使用切片:slice
def reversed_string(a_string):
return a_string[::-1]
def reverse_string_readable_answer(string):
return ''.join(reversed(string))
这种做法其实非常不推荐的,因为,记住,Python中字符串是不可变的——针对下面的算法,乍看起来像在的new_string上添加一个字符,但理论上它每次都创建一个新字符串!(一定程度上,各个IDE可能会一定程度针对此做一定的编译优化)
def reverse_a_string_slowly(a_string):
new_string = ''
index = len(a_string)
while index:
index -= 1 # index = index - 1
new_string += a_string[index] # new_string = new_string + character
return new_string
def reverse_a_string_more_slowly(a_string):
new_strings = []
index = len(a_string)
while index:
index -= 1
new_strings.append(a_string[index])
return ''.join(new_strings)
https://stackoverflow.com/questions/931092/reverse-a-string-in-python