A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://mail.python.org/pipermail/python-list/2001-April/076524.html below:

Stepping backwards in for loop?

Stepping backwards in for loop?Steve Purcell stephen_purcell at yahoo.com
Sat Apr 14 10:49:25 EDT 2001
Gustaf Liljegren wrote:
> Can't figure out how to step backwards, character by character in a string. 
> I was looking for a loop countruct with a counter to handle this, but the 
> for loop in Python doesn't let me step backwards. What is the alternative?

An alternative is to use a forward loops but use negative indexes for the
string, which go from -1 to (-1 - len(s)):

    >>> s = "forwards"
    >>> backwards = []
    >>> for i in range(1, 1+len(s)):
    ...   backwards.append(s[-i])
    ... 
    >>> backwards
    ['s', 'd', 'r', 'a', 'w', 'r', 'o', 'f']
    >>> 

-Steve

-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Any opinions expressed herein are my own and not necessarily those of Yahoo


More information about the Python-list mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4