Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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**

like image 461
Juliana Avatar asked Jan 25 '26 17:01

Juliana


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**
like image 111
Andrej Kesely Avatar answered Jan 27 '26 06:01

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!