Small question on indexes

Let’s say we have the string

smurf = 'dvdf'

if I try to use the index function for d, will I always get the same index or can I get the index for the second d as well (an index of 2)




What do you mean by second d? How would you specify that differently when calling the str method?

You’re not specifying nth
You’re specifying a value

Look for something like findall instead

There are two ds each with a different index. I was wondering also how one would specify differently, if there is another method

>>> help(''.index)
Help on built-in function index:

index(...) method of builtins.str instance
    S.index(sub[, start[, end]]) -> int
    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    Raises ValueError when the substring is not found.

…and read documentation of things.

where did you find documentation?

look at the first line

For specifically strings you’ve got regex:

>>> list(re.finditer('d', 'dvdf'))
[<re.Match object; span=(0, 1), match='d'>, <re.Match object; span=(2, 3), match='d'>]

It’s also trivial to implement (all) index, it’s a for-loop with == comparisons

I suppose I could use a counter

You can similarly zip with indices and then filter, but … yeah you’d use a loop in python

> "dvdf"      <-- start with the string

> "dvdf" & zip [0..]      <-- pair with indices

> "dvdf" & zip [0..] & filter (snd >>> (=='d'))   <-- filter by value

> "dvdf" & zip [0..] & filter (snd >>> (=='d')) <&> fst  <-- keep only index

In python you can count up from zero with itertools.count
there’s also a function that does this and zips it with the values, enumerate

[i for i, x in zip(count(), 'dvdf') if x == 'd']
[i for i, x in enumerate('dvdf') if x == 'd']