温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

【Python】【翻转字符串】

发布时间:2020-05-30 09:41:03 来源:网络 阅读:357 作者:醉月夜 栏目:编程语言

要求:在Python环境下用尽可能多的方法反转字符串,例如将s = "abcdef"反转成 "fedcba"
【1】:使用字符串切片
result = s[::-1]
【2】:使用列表的reverse方法

l = list(s)
l.reverse()
result = "".join(l)

【3】:使用reduce
result = reduce(lambda x,y:y+x,s)
【4】:使用递归函数

def fun(s):
    if len(s)<1:
            return s
    return func(s[1:])+[0]
result = func(s)

【5】:使用栈

def func(s):
    l = list(s) #模拟全部入栈
        result = ""
        while len(1)>0:
            result += 1.pop() #模拟出栈
        return result
result = func(s)

【6】:for循环

def func(s):
    result = ""
    max_index = len(s)-1
    for index,value in enumerate(s):
        result += s[max_index-index]
    return result
result = func(s)
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI