Display list elements as if they were typed in

Viewed 45

Here's the code:

test = ['26', 1, '050120', '084922', u'43034775', u'RRR', '', None]
print(', '.join(test))

It says:

TypeError: sequence item 1: expected str instance, int found

Is there a way to join without looking at element type?

', '.join(str(v) for v in test)

is not a good solution. It prints:

26, 1, 050120, 084900, 21747, 1200.0, X, X, 18034775, 5TDDK3DC4BS029227, , None

I want to leave element type as it is and print out as it is:

'26', 1, '050120', '084922', u'43034775', u'RRR', '', None
3 Answers

You can use the repr builtin.

print(', '.join(map(repr, test)))

This produces the desired output because

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval()

Example:

>>> str(1)
'1'
>>> str('1')
'1'
>>> repr(1)
'1'
>>> repr('1')
"'1'"

If it is just for printing purpose :

test = ['26', 1, '050120', '084922', u'43034775', u'RRR', '', None]

print(str(test)[1:-1])

To the your expected output '26', 1, '050120', '084922', u'43034775', u'RRR', '', None. Use the formatting of the list and remove the brackets

test = ['26', 1, '050120', '084922', u'43034775', u'RRR', '', None]
print(str(test).strip("[]")) # '26', 1, '050120', '084922', '43034775', 'RRR', '', None
Related