Python中的字符串反转

来源:互联网 发布:搜索图片的软件 编辑:程序博客网 时间:2024/05/29 16:31

性能最佳者

推荐方法,使用切片: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