简体   繁体   中英

Adding numbers to a list of strings

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 use enumerate , just specify start and it'll start from 1 :

rader = ['{} {}'.format(i,s) for i,s  in enumerate(rader, start=1)]

And if you just want to print it that way:

print(*('{} {}'.format(i,s) for i,s in enumerate(rader, start=1)), sep=', ')

Output:

1 John, 2 Eric, 3 Samuel

You can pass additional arguments for range function, for example:

 for i in range(1,len(rader))

More about range function

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM