Issue
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
Solution
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'"
Answered By - timgeb
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.