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?
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?
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
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