How do I use a C-style for loop in Python?

后端 未结 7 1639
南旧
南旧 2020-12-01 06:17

I want to use the traditional C-style for loop in Python. I want to loop through characters of a string, but also know what it is, and be able to jump through characters (e.

7条回答
  •  天涯浪人
    2020-12-01 06:37

    The Python for loop always has foreach semantics. You can, however, do this:

    for i in xrange(10):
        print i
    

    This is very much like a C for loop. xrange (or range, as it was renamed in Python 3) is a constructor for a Python object that iterates through a range of numbers. See the docs for more information.

提交回复
热议问题