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.