Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a string with separators from a list of numbers using Python3

I have a list of numbers:

list1 = [1, 2, 3, 4]

I would like to create a string as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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:

  1. Format the number into the string '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,

  1. Join all the formatted strings in this list with ' 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading