Im trying to modify a list of strings so the elements will have element numbers at front starting from 1
.
For example:
['John', 'Eric', 'Samuel']
becomes ['1 John', '2 Eric', '3 Samuel']
Here is the code i have so far:
for i in range(len(rader)):
rader[i] = '{}{}{}'.format(i," ",rader[i])
This adds a number before but the problem is that it gives the first string number zero, how do I work around this?
You can pass i + 1
to format()
:
for i in range(len(rader)):
rader[i] = '{}{}{}'.format(i + 1," ",rader[i])
# ^^^^^
But there exists a more elegant way:
for i, name in enumerate(rader):
rader[i] = '{} {}'.format(i + 1, name)
You can pass additional arguments for range function, for example:
for i in range(1,len(rader))
But for this solution you'd need to re-numerate rest of you code though, so it's probably not best idea.
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.