0

Is there a simpler way (without for loop) to include the list index in a joint together string?
My current code is:

sep = ' - '
a = 'apple - banana - lemon - melon'
b = a.split(sep)
c = ''

for item in b:
    c += str(b.index(item)+1)+'.'+item+sep

d = c[:len(c)-len(sep)]
print(d)
lmocsi
  • 435
  • 2
  • 12
  • Do you want the indexes in a string, or a subset of [(index, substring), ...]? – Jab Sep 14 '18 at 19:47
  • This can be more concisely expressed as `sep.join('{}.{}'.format(i, x) for i, x in enumerate(b, start=1))` – Patrick Haugh Sep 14 '18 at 19:53
  • Thanks Patrick, that's what I was looking for. After the first two lines, it can be condensed into one line: `d = sep.join('{}.{}'.format(i, s) for i,s in enumerate(a.split(sep), start=1)) ` – lmocsi Sep 14 '18 at 20:02

1 Answers1

0

Here’s what I think you’re looking for if you’re trying to steer away from for loops:

Also for further information check out: enumerate, and join

sep = ' - '
a = 'apple - banana - lemon - melon'
b = a.split(sep) #Turns the string into a list of “items

b = enumerate(b) #Turns the items list into [(item_index, item), ...]
c = f"{b[1]}.{b[0]}" #Formats item.index how you were
d = sep.join(c) #puts them all together in a neat little string separated by “sep”

e = d[:len(d)-len(sep)]
print(e)

But this step by step to break it down simply. Below are b, c, and d put into 2 lines.

sep = ' - '
a = 'apple - banana - lemon - melon'

b = enumerate(a.split(sep))
c = sep.join(f"{b[1]}.{b[0]}")

d = c[:len(c)-len(sep)]
print(d)

Although, if I’m not mistaken, a list comprehension would still be faster. If at least for the map.

Edit: Credit goes to @Patrick Haugh. For the list comprehension.

d = sep.join('{}.{}'.format(i, s) for i,s in enumerate(a.split(sep), start=1)

I also fixed mine up based on yours as mine was joining a str and int and my thoughts were he was trying to not use for loop.

Jab
  • 21,612
  • 20
  • 66
  • 111