I have a list of numbers:
list1 = [1, 2, 3, 4]
I would like to create a string as follows:
Contains([saleID],"1") OR
Contains([saleID],"2") OR
Contains([saleID],"3") OR
Contains([saleID],"4")
I tried the following code:
print('Contains([saleID],"'.join(str(x) for x in list1).join('" OR'))
But I get the following output:
"1Contains([saleID],"2Contains([saleID],"3Contains([saleID],"4 1Contains([saleID],"2Contains([saleID],"3Contains([saleID],"4O1Contains([saleID],"2Contains([saleID],"3Contains([saleID],"4R
Please advise
x.join(lst)
joins the elements of lst
using x
as a separator. Knowing this, you want to use x = ' OR\n'
because that's what is repeated. The elements of lst
can contain the rest of each line, i.e. 'Contains([saleID],"{num}")'
There are two parts to this operation:
'Contains([saleID],"{num}")'
, which gives a list containing four strings as shown below:>>> lst = [f'Contains([saleID],"{num}")' for num in list1]
['Contains([saleID],"1")',
'Contains([saleID],"2")',
'Contains([saleID],"3")',
'Contains([saleID],"4")']
And,
' OR\n'
>>> result = ' OR\n'.join(lst)
'Contains([saleID],"1") OR\nContains([saleID],"2") OR\nContains([saleID],"3") OR\nContains([saleID],"4")'
Print result
to see that we have the desired value:
Contains([saleID],"1") OR
Contains([saleID],"2") OR
Contains([saleID],"3") OR
Contains([saleID],"4")
Of course, you can do this all in a single line with:
>>> result = ' OR\n'.join(f'Contains([saleID],"{num}")' for num in list1)