1

Suppose I have the following list:

temp = ['Ok', 'Whoa. Robot?']

How do I get a string that looks like

"1) 'Ok', 2) 'Whoa. Robot?'"

I'm trying to do this for a list comprehension. I can obviously join them using:

" ".join(temp)

I can do it in a loop in a fairly ugly way:

mystring = ""
temp = ['Ok', 'Whoa. Robot?']
for i in range(len(temp)):
    mystring += str(i) + ") " + temp[i] + "  "

Is there a pythonic way to do it in one step with a list comprehension?

user1357015
  • 11,168
  • 22
  • 66
  • 111

1 Answers1

6
mystring = ', '.join(["{}) {!r}".format(i, s) for i, s in enumerate(temp, 1)])

The {!r} conversion produces the repr() representation of the string, so you get quotes around the parts, but note that the quotes may change depending on the string's content, or in other words if it contains quotes itself.

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
  • You don't need the list comp brackets inside of the `join`. It will evaluate the generator. – James Dec 24 '17 at 21:05
  • 1
    @James See e.g. [this thread](https://stackoverflow.com/questions/37782066/list-vs-generator-comprehension-speed-with-join-function). `str.join` is one of the functions that are faster with lists than with generators. – user2390182 Dec 24 '17 at 21:07