Reputation: 3175
I have a list of integers and I want to concatenate them in a loop.
This is what I have so far
a = [3, 4, 6]
temp = []
for i in a:
query = 'Case:' + str(i)
temp.append(query)
print(' OR '.join(temp))
>>> Case:3 OR Case:4 OR Case:6
Is there a better way to write this?
Upvotes: 1
Views: 7043
Reputation: 1844
You could also use a comprehension:
>>> a = [3, 4, 6]
>>> ' OR '.join([ "Case " + str(x) for x in a ])
'Case 3 OR Case 4 OR Case 6'
Upvotes: 1
Reputation: 10218
Completing the idea from @Joshua K for using map and lambda (although I think the list comprehension is a better solution):
>>> a = [3, 4, 6]
>>> 'OR '.join(map(lambda i: 'Case:' + str(i) + ' ', a))
Case:3 OR Case:4 OR Case:6
Upvotes: 0
Reputation: 2537
You can also use map and lambda expressions:
temp = map(lambda x: 'Case: '+str(x), a)
Upvotes: 2
Reputation: 90899
Yes, you can use generator expression and str.join
,
' OR '.join('Case: {}'.format(i) for i in a)
Example/Demo -
>>> a = [3, 4, 6]
>>> ' OR '.join('Case: {}'.format(i) for i in a)
'Case: 3 OR Case: 4 OR Case: 6'
Upvotes: 2