I have created some code to determine the position of characters in a string. However, the count starts from 0 not 1.
string="pandas"
for i,c in enumerate(string):
if "a"==c: print i
I would also be interested in a more naive solution to my problem which didn't use enumerate.
Start enumerate at 1
as follows:
for i, c in enumerate(string, 1):
if "a"==c: print i
It seems you are using Python 2, so in case you want to use Python 3, use:
for i, c in enumerate(string, 1):
if "a"==c: print(i)
A more naive solution:
for i in range(len(string)):
if "a" == string[i]:
print(i + 1)
you could also use regex:
import re
[m.start() for m in re.finditer('a', string)]
or
[m.start()+1 for m in re.finditer('a', string)]
depending on what you want
string="pandas"
for i,c in enumerate(string,1):
if "a"==c: print(i)
or a more python solution using list comprehension
and regex
:
[x.end() for x in re.finditer('a', string)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.