1

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?

1
  • 1
    A bit shorter: ' OR '.join('Case:' + str(i) for i in a) Commented Aug 7, 2015 at 2:18

4 Answers 4

2

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'
Sign up to request clarification or add additional context in comments.

5 Comments

yea , though only a slight difference :) .
Ditto -- beat me to it by a minute!
Anyway.. enjoy.. I deleted my answer. the net result is the same.. :)
Thanks everyone who answered! This is great! This is what I am looking for. I just didn't realised it's called generator expression.
I thought I'd make an answer just because I love comprehensions :p
2

You can also use map and lambda expressions:

temp = map(lambda x: 'Case: '+str(x), a)

2 Comments

This returns a list not a string. You can convert it to the required output by chaining it to a join like this: ' '.join(map(lambda i: 'Case:' + str(i) + ' OR', a))
I took his code from above and split the converting and joining in two parts like in his code. That is only the line für converting (translation of his for loop).#
1

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'

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.