Python如何实现字符串的反转

avatar
作者
猴君
阅读量:0

可以使用以下方法来实现字符串的反转:

  1. 使用切片操作符[::-1]
def reverse_string(s):     return s[::-1]  s = "hello" reversed_s = reverse_string(s) print(reversed_s) 
  1. 使用循环逆序遍历字符串
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) 
  1. 使用递归
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) 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!