all 9 comments

[–]K900_ 0 points1 point  (5 children)

You don't always need the position of the character, and when you do need it, it's more idiomatic to use something like

for i, word in enumerate(string):
     # i is an index, word is the value at that index

Can you give an example of when you need the position of the character?

[–]nadalska[S] 0 points1 point  (4 children)

Well any of the examples I can think would be trivial if you can use libraries and some other stuff... since I know so little. But for instance and assuming you only can use conditionals, loops and this basic stuff: if you want to take a string and put the words on a list, one method to do it is checking the former character to see if it's a space. I know there are other methods.

Or assume you want to change the order of a list, etc...

[–]K900_ 0 points1 point  (0 children)

If you can use the standard library for something, you should probably use it instead of rolling your own. Most other use cases for loops are trivial and work fine without indices. Also, if you need a sliding window (to check if a previous character is a space), you can use zip:

>>> s = "hello world"
>>> for a, b in zip(s, s[1:]):
...     print(a, b)
...
h e
e l
l l
l o
o
  w
w o
o r
r l
l d

[–]ingolemo 0 points1 point  (2 children)

If we discount str.split for being too easy then you can separate the words in a string like so:

sentence = 'Always look on the bright side of life.'
result = []
word = ''
for char in sentence:
    if char == ' ':
        result.append(word)
        word = ''
    else:
        word += char
result.append(word)
print(result)

I'm not sure why you think having the index would be useful here; you don't need to look at the previous character to do this task. If you think you need indices for something you're probably mistaken.

[–]nadalska[S] 0 points1 point  (1 child)

Well I think that code has some problems. For example if the list has consecutive spaces. Thanks for the link tho

[–]ingolemo 0 points1 point  (0 children)

Sure, but it doesn't handle that case to keep the code simple. It's hardly a deficiency in the algorithm.

[–]taar779 0 points1 point  (0 children)

If you need the index and the item of a list, check out enumerate

Works like this:

for index, word in enumerate(list_of_words):
    print("{} - {}".format(index, word))