ITPub博客

首页 > IT职业 > IT图书 > 如何实现python字符串反转?

如何实现python字符串反转?

IT图书 作者:xduu 时间:2021-09-11 10:05:41 0 删除 编辑

Python中字符串反转常用的五种方法:使用字符串切片、使用递归、使用列表reverse()方法、使用栈和使用for循环。

1、使用字符串切片(最简洁)

s = "hello"
reversed_s = s[::-1]
print(reversed_s)

>>> olleh

2、使用递归

def reverse_it(string):
  if len(string)==0:
    return string
  else:
    return reverse_it(string[1:]) + string[0]
    print "added " + string[0]
 
string1 = "the crazy programmer"
string2 = reverse_it(string1)
 
print "original = " + string1
print "reversed = " + string2

3、使用列表reverse()方法

In [25]: l=['a', 'b', 'c', 'd']
    ...: l.reverse()
    ...: print (l)
['d', 'c', 'b', 'a']

4、使用栈

def rev_string(a_string):
    l = list(a_string) #模拟全部入栈
    new_string = ""
    while len(l)>0:
        new_string += l.pop() #模拟出栈
    return new_string

5、使用for循环

#for循环

    def func(s):
    	r = ""
    	max_index = len(s) - 1
    	for index,value in enumerate(s):
    		r += s[max_index-index]
    	return r
    r = func(s)

以上就是Python中字符串反转常用的五种方法,希望能对你Python字符串的学习有所帮助~

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2195/viewspace-2831707/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-16

  • 博文量
    84
  • 访问量
    1003