1

I have a list with mixed object types (strings and ints), and what I want to do is .join that list into a string where each string is wrapped in quotes BESIDES the integers. So for example if I had this list:

sample_list = ['abcd', 'chicken', 'wasd', 1, 'blah', 3, 'foo', 'bar']

I would like to produce the following string from it:

sample_string = "('abcd', 'chicken', 'wasd', 1, 'blah', 3, 'foo', 'bar')"

This is what I have:

sample_string = "(" + ', '.join("'{0}'".format(item) for item in sample_list if type(item) is not int) + ")"

Clearly my code is wrong because my integer values end up being dropped due to the 'if' statement, but I've gotten stuck figuring out an elegant way to produce the string I desire, and was wondering if anyone could help with providing some tips on how to do so.

Thanks in advance!

DGav
  • 201
  • 2
  • 12

2 Answers2

6

How about:

str(tuple(sample_list))

Returns:

"('abcd', 'chicken', 'wasd', 1, 'blah', 3, 'foo', 'bar')"
Anton vBR
  • 15,331
  • 3
  • 31
  • 42
2

You could use "(" + ", ".join(map(repr, sample_list)) + ")". Note that this will use different quotes depending on what is in the string, but this could be desirable. To fix the code in your question, you could use the ternary operator, instead of with if as a condition for the comprehension.

internet_user
  • 2,932
  • 1
  • 16
  • 26