Python中的字符串反转

性能最佳者

推荐方法,使用切片:slice

def reversed_string(a_string):
    return a_string[::-1]

可读性强

def reverse_string_readable_answer(string):
    return ''.join(reversed(string))

中规中矩

这种做法其实非常不推荐的,因为,记住,Python中字符串是不可变的——针对下面的算法,乍看起来像在的new_string上添加一个字符,但理论上它每次都创建一个新字符串!(一定程度上,各个IDE可能会一定程度针对此做一定的编译优化)

def reverse_a_string_slowly(a_string):
    new_string = ''
    index = len(a_string)
    while index:
        index -= 1                    # index = index - 1
        new_string += a_string[index] # new_string = new_string + character
    return new_string

中规中矩最佳实践

def reverse_a_string_more_slowly(a_string):
    new_strings = []
    index = len(a_string)
    while index:
        index -= 1                       
        new_strings.append(a_string[index])
    return ''.join(new_strings)

https://stackoverflow.com/questions/931092/reverse-a-string-in-python

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值