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

Python joining an array into a single line with a new line for every two elements

I have an array with 8 items like the below array (dummy data), I only want the first 6 items. I can’t seem to get .join correct.

["MR_L: ", 20, "Time: ", "10:00", "Email: ", "Testing@test", "Telephone: ", 0002411212]

I want the out come to be in a string:

"MR_L: 20
Time: 10:00
Email: Testing@test"

I’ve tried a for loop like: for index in range (0, 5, 2) then use index -1. It is important this is all in one string as I am using a function that can only take a single string as an argument. When I use join I get a memory error.

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

>Solution :

If the integer value(s) in your list are valid then you could do this:

mylist = ["MR_L: ", 20, "Time: ", "10:00", "Email: ", "Testing@test", "Telephone: ", 2411212]

parts = []

for i in range(0, min(6, len(mylist)), 2):
    parts.append('{}{}'.format(*mylist[i:i+2]))

print(*parts, sep='\n')

Output:

MR_L: 20
Time: 10:00
Email: Testing@test
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