-4

i have a list of strings like this ['apple', 'banana', 'nothing']

and i'd like to convert it into something like this 1-apple 2-banana 3-nothing i know that i can use join for static data but it's not helping or maybe this:

range(10).join(...

but it won't work

1
  • The code you posted is not valid Python, so of course "it won't work". Feb 8 at 13:40

1 Answer 1

0

You can do this:

t = ['apple', 'banana', 'nothing']
res = " ".join([str(ind + 1) + '-' + item for ind, item in enumerate(t)])
print(res)

outputs:

1-apple 2-banana 3-nothing
5
  • 1
    That's a really inelegant way to enumerate
    – deceze
    Feb 8 at 13:45
  • Indeed it is :) I changed it to enumerate @deceze .
    – sagi
    Feb 8 at 13:46
  • i don't want to content of join affects on range of numbers
    – anonymouse
    Feb 8 at 13:47
  • 4
    @anonymouse Wat?
    – deceze
    Feb 8 at 13:47
  • Since you really start enumerating with 1, you could express that more directly with enumerate(t, start=1) or enumerate(t, 1). Feb 8 at 19:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.