3

If I have a string e.g. s = '1084271054', and want to print all index locations of 0 e.g:

0 - 1, 7

What would be the most basic way to go about this?

Michał Zaborowski
  • 3,911
  • 2
  • 19
  • 39
Budju
  • 31
  • 1
  • 1
    SO is not a coding service. Show some of your work in regards to solving this problem and you might get some help. – AmmoPT Aug 30 '18 at 10:46
  • Possible duplicate of [python - find char in string - can I get all indexes?](https://stackoverflow.com/questions/11122291/python-find-char-in-string-can-i-get-all-indexes) – Space Impact Aug 30 '18 at 10:47
  • Sorry I'm a nub – Budju Aug 30 '18 at 11:37

3 Answers3

2
[i for i, c in enumerate(s) if c=='0']
Out: [1, 7]
SpghttCd
  • 10,510
  • 2
  • 20
  • 25
1

Maybe something like

>>> idx=[i for i in range(len(s)) if s[i]=='0']
>>> idx
[1, 7]

Edit:

>>> print ', '.join(str(i) for i in idx)
1, 7
duntel12
  • 103
  • 5
0

Pass the string into the enumerate function which returns an iterable of the indexes and characters. Then you can iterate over this and check if the character is '0' and if it is, print the index:

for i,c in enumerate(s):
    if c == '0':
        print(i)

which outputs:

1
7

If you want them on one line separated by commas, then you can use str.join with a generator:

print(', '.join(str(i) for i,c in enumerate(s) if c == '0'))

which gives:

1, 7
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54