Python3实现:字符串反转

 
  
#方式一(切片) astr = 'abcdef' bstr = astr[::-1] print(bstr) #方式二 def myreverse (s): l = list(s) l.reverse() print("".join(l)) myreverse('abcdef') #方式三(递归) def myreverse1 (s): if s == "": return s else: return myreverse1(s[1:]) + s[0] print(myreverse1('abcdef')) #方式四(逐个字符处理) def myreverse2 (s): t = '' r = len(s) - 1 while r >= 0: t = t + s[r] r -= 1 return t print(myreverse2('abcdef'))

#方式五(使用sorted()方法)
def myreverse3(s):
    l = list(s)

    newl = sorted(l,key = None,reverse = True)
    news = ''.join(newl)
    return news

print(myreverse3('abcdef'))

你可能感兴趣的:(Python)