0
>>> bob = "bob"
>>> range(0, len(bob))
[0, 1, 2]
>>> bob[0:2]
'bo'
>>> bob[0:3]
'bob'

Is there a convenient way to iterate over strings in python when I need the index number? If I make a for loop with range(0, len(astring)), it will only end up going up to the second-to-last character: I would instead have to write range(0, len(astring) + 1), which is kind of annoying. I can't do for c in astring because I am taking substrings. Suggestions?

3
  • 2
    Why is it annoying to add one? Commented Feb 8, 2014 at 21:22
  • I suppose you could always write a wrapper function to replace len such that it returns the result of len but with 1 added to it. Commented Feb 8, 2014 at 21:22
  • @BrenBarn There's good reason to have separate notations for inclusive and exclusive bounds. For example, [x, y] vs [x, y) in mathematics, and x to y vs x until y in the scala core library. It's a more direct expression of your intention. Commented Feb 8, 2014 at 21:45

2 Answers 2

3

Use enumerate:

for i,c in enumerate('bob'):
    print('{}: {}'.format(c,i))

b: 0
o: 1
b: 2

Your bit about "substrings" is a bit under-specified, but chances are slicing will do what you need:

s = 'banana'

for i,c in enumerate(s):
    print(s[i:])

banana
anana
nana
ana
na
a

notably, you can leave off either the start or end bound to a slice (or both!) and the slice will just go all the way up to that end.

Sign up to request clarification or add additional context in comments.

2 Comments

I got the impression the OP wanted to loop over substrings, not characters.
@DSM well then just replace 'bob' with bob's substring, no?
1

Suppose you have:

>>> st='a string with substrings'

Of course it is easy to just split that:

>>> st.split()
['a', 'string', 'with', 'substrings']

But suppose you want to deal with indices of the string based on some condition.

You can define the indices that you want (trivially by spaces here, but could be some other condition):

>>> sub_strings=[0]+[i+1 for i, c in enumerate(st) if c.isspace()]+[len(st)]

Then you can use slice like so:

>>> for t in zip(sub_strings, sub_strings[1:]):
...    print st[slice(*t)], t
... 
a  (0, 2)
string  (2, 9)
with  (9, 14)
substrings (14, 24)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.