向后循环 python 字符串的最佳方法 [英] Best way to loop over a python string backwards

查看:25
本文介绍了向后循环 python 字符串的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

向后循环 python 字符串的最佳方法是什么?

What is the best way to loop over a python string backwards?

对于 -1 偏移的所有需要​​,以下似乎有点尴尬:

The following seems a little awkward for all the need of -1 offset:

string = "trick or treat"
for i in range(len(string)-1, 0-1, -1):
    print string[i]

下面看起来更简洁,但它实际上生成了一个反转的字符串,从而有轻微的性能损失吗?

The following seems more succinct, but is it actually generate a reversed string so that there is a minor performance penalty?

string = "trick or treat"
for c in string[::-1]:
    print c

推荐答案

试试反向内置:

for c in reversed(string):
     print c

reversed() 调用将创建一个迭代器而不是复制整个字符串.

The reversed() call will make an iterator rather than copying the entire string.

PEP 322 详细说明了 reversed() 及其相对于其他方法的优势.

PEP 322 details the motivation for reversed() and its advantages over other approaches.

这篇关于向后循环 python 字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆