How to print a list comprehension with strings and integers and add a symbol only to the strings?

Viewed 48

I have a mixed list of integers and strings and I need to print '**' after strings only.

data = [4, 'Fred', 'London', 34, 78, '@#=£', 89, 'Ice cream', 'Hamilton', 12, 'tingle']
[print(data, end='**') for data in data if isinstance(data, str)]

This is the output:

Fred**London**@#=£**Ice cream**Hamilton**tingle**

Desired output:

4, Fred**, London**, 34, 78, @#=£**, 89, Ice Cream**, Hamilton**, 12, tingle**

1 Answers

Your if is now filtering the list data. Put it before the for. Also, use str.join to join the various strings with , :

data = [4, 'Fred', 'London', 34, 78, '@#=£', 89, 'Ice cream', 'Hamilton', 12, 'tingle']

print( ', '.join('{}**'.format(item) if isinstance(item, str) else str(item) for item in data) )

Prints:

4, Fred**, London**, 34, 78, @#=£**, 89, Ice cream**, Hamilton**, 12, tingle**
Related