Python: reverse string
-
''.join(reversed('abcd'))
- 切片
p[::-1] p[-1::-1] p[-1:-(len(p)+1:-1]
-
from functools import reduce b = 'rty' print(reduce(lambda prev, curr: curr + prev, b)) print(reduce(lambda prev, curr: curr + prev, b, '!'))
- recursion
b = 'rtyu' def bud(s: str): if len(s) == 1: return s return bud(s[1:]) + s[0] print(bud(b))
- simulate stack
b = 'rtyu' def bud(s: str): vale = list(s) ret = '' while vale: ret += vale.pop(-1) return ret print(bud(b))
- exploit circulate
b = 'rtyu' def bud(s: str): era = '' # 0 1 .. len(s)-1 # for p in range(len(s)): # era += s[-p - 1] # era += s[len(s) - 1 - p] # len(s)-1 ... 1 0 # for p in range(len(s) - 1, -1, -1): # era += s[p] for i, _ in enumerate(s): era += s[len(s) - 1 - i] return era print(bud(b))
-
b = 'rtyu' print(b[slice(-1, -(len(b) + 1), -1)])