0

I have a list containing number and string:

words = ['hello', 2, 3, 4, 5]

I want a string:

"'hello', 2, 3, 4, 5"

What's the easiest way to do this with Python

philipxy
  • 14,867
  • 6
  • 39
  • 83
  • 1
    Does this answer your question? [printing double quotes around a variable](https://stackoverflow.com/questions/20056548/printing-double-quotes-around-a-variable) – sahasrara62 Jul 10 '20 at 05:49
  • What do you want to happen if another string is present? e.g. `words = ['hello', 2, 3, 'there', 5]`? And what if `words = [1, 2, 'hello', 4, 5]` Convert any string or just the first element? – Pynchia Jul 10 '20 at 05:52
  • `words = ['hello', 2, 3, 'there', 5]` This is also possible or `words = ['hello',' 2', '3', '4', '5']` In this one, I have to change first one which is not a number. – Bipul singh kashyap Jul 10 '20 at 06:16

4 Answers4

3
words = ['hello', 2, 3, 4, 5]
", ".join([str(x) if isinstance(x,int) else "'{}'".format(x) for x in words])

Output:

"'hello', 2, 3, 4, 5"
bigbounty
  • 16,526
  • 5
  • 37
  • 65
2

One way using str.strip:

str(words).strip("[]")

Output:

"'hello', 2, 3, 4, 5"
Chris
  • 29,127
  • 3
  • 28
  • 51
0

If i understand you, this is my solution:

words = ['hello', 2, 3, 4, 5]

result = '''"{}"'''.format(", ".join(map(lambda x: "'{}'".format(str(x)) if isinstance(x, str) else str(x), words)))

print(result)

Output is:

"'hello', 2, 3, 4, 5"
moabson
  • 21
  • 3
-1

Do this:

words = ['hello', 2, 3, 4, 5]
print(','.join([str(elem) if isinstance(elem,int) else "'{}'".format(elem) for elem in words]) )

Output :

'hello',2,3,4,5
Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53