阅读量:0
可以使用以下方法来实现字符串的反转:
- 使用切片操作符[::-1]
def reverse_string(s): return s[::-1] s = "hello" reversed_s = reverse_string(s) print(reversed_s)
- 使用循环逆序遍历字符串
def reverse_string(s): reversed_s = "" for char in s: reversed_s = char + reversed_s return reversed_s s = "hello" reversed_s = reverse_string(s) print(reversed_s)
- 使用递归
def reverse_string(s): if len(s) == 0: return s else: return reverse_string(s[1:]) + s[0] s = "hello" reversed_s = reverse_string(s) print(reversed_s)