如何使用字符串和整数打印列表理解并仅向字符串添加符号?
How to print a list comprehension with strings and integers and add a symbol only to the strings?
我有一个整数和字符串的混合列表,我只需要在字符串后打印“**”。
data = [4, 'Fred', 'London', 34, 78, '@#=£', 89, 'Ice cream', 'Hamilton', 12, 'tingle']
[print(data, end='**') for data in data if isinstance(data, str)]
这是输出:
Fred**London**@#=£**Ice cream**Hamilton**tingle**
期望的输出:
4, Fred**, London**, 34, 78, @#=£**, 89, Ice Cream**, Hamilton**, 12, tingle**
您的 if
正在过滤列表 data
。把它放在 for
之前。此外,使用 str.join
将各种字符串与 ,
:
连接起来
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) )
打印:
4, Fred**, London**, 34, 78, @#=£**, 89, Ice cream**, Hamilton**, 12, tingle**
我有一个整数和字符串的混合列表,我只需要在字符串后打印“**”。
data = [4, 'Fred', 'London', 34, 78, '@#=£', 89, 'Ice cream', 'Hamilton', 12, 'tingle']
[print(data, end='**') for data in data if isinstance(data, str)]
这是输出:
Fred**London**@#=£**Ice cream**Hamilton**tingle**
期望的输出:
4, Fred**, London**, 34, 78, @#=£**, 89, Ice Cream**, Hamilton**, 12, tingle**
您的 if
正在过滤列表 data
。把它放在 for
之前。此外,使用 str.join
将各种字符串与 ,
:
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) )
打印:
4, Fred**, London**, 34, 78, @#=£**, 89, Ice cream**, Hamilton**, 12, tingle**