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

Question:

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.

Asked By: OttoLuck

||

Answers:

There are various ways to do it. One way is like this:

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

# STEP 1. convert all items to str type and put n (newline) to every second items.
str_data = [str(item) if i % 2 == 0 else str(item)+"n" for i, item in enumerate(data)]
print(str_data)
# ['MR_L: ', '20n', 'Time: ', '10:00n', 'Email: ', 'Testing@testn', 'Telephone: ', '2411212n']

# STEP 2. combine the first six items 
result = "".join(str_data[:6])[:-1] # [:-1] to remove last "n"
print(result)
"""
MR_L: 20
Time: 10:00
Email: Testing@test
"""
Answered By: Park

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
Answered By: Fred

Consider using the pairwise() implementation from Iterating over every two elements of a list to solve that part of your problem.

Next you can convert your pairs into strings:

[f"{k}{v}" for k, v in pairwise(allItems)]

Omit the last pair (two elements):

[f"{k}{v}" for k, v in pairwise(allItems[:-2])]

And join with newlines:

"n".join(f"{k}{v}" for k, v in pairwise(allItems[:-2]))
Answered By: johnsyweb

I think your data suggests a pairwise grouping:

from itertools import pairwise

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

# group in pairs [["MR_L: ", 20], ...]
pairs = pairwise(data) # returns an iterable

# you then join pairs (you need 3 pairs for 6 items)
"n".join(f"{k}{v}" for k, v in list(pairs)[:3])

Answered By: Eelke van den Bos

You can try using generator expression and zip of the list from index 0 to length of the list -2 with 2 step and from index 1 likewise:

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

outPut = lambda lst: 'n'.join(f'{a}{b}' for a,b in zip(lst[:-2:2],lst[1::2]))

print(outPut(mylist))

# MR_L: 20
# Time: 10:00
# Email: Testing@test
Answered By: Arifa Chan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.