0

I need to concatenate strings in a list sequentially to join the two parts of words that were separated by line breaks. Can someone help me?

list = ["a", "b", "c", "d"]

Required output:

"ab"
"cd"   
2
  • Are the variables string with line break in you want to remove? Commented Feb 28, 2019 at 12:26
  • Is the List Fix contains element Commented Feb 28, 2019 at 12:26

8 Answers 8

2

Assuming you want to join pairs of consecutive items:

>>> lst = ['a', 'b', 'c', 'd']
>>> list(map(''.join, zip(*([iter(lst)]*2))))
['ab', 'cd']

Here, zip(*([iter(lst)]*2)) is a common recipe for pairs of elements by ziping two instances of the same iterator on the list, but there are many other ways to do the same.

(Note: Renamed list to lst for not shadowing the builtin type)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!!
2
for i in range(0, len(l), 2):
    ''.join(l[i:i + 2])

2 Comments

Thank you again! Is this another method?
It does the job as all the rest. I like it because it is not tricky but just a normal loop.
2

Using a shared iterator,

>>> [x + next(itr) for itr in [iter(lst)] for x in itr]
['ab', 'cd']

In the forthcoming Python 3.8 (ETA fall 2019), that can be more succinctly written (I believe) as

[x + next(itr) for x in (itr:=iter(lst))]

4 Comments

Nice. Only approach so far that will raise an exception if the list has an odd length instead of just omitting the last item, but a bit nasty to extend to more than two elements.
Thank you so much!
BTW, do you know why they don't use e.g. for x in (iter(lst) as itr), reusing as from import, with and except instead of introducing new :=?
The decision to support some form of assignment expression was made quickly. The debate over the exact syntax to use dragged on... and on... and on. as was eventually rejected to avoid adding another set of slightly different semantics on top of what existing uses of as already defined. See PEP 572 for all the gory details.
1

Given a list,

L=['a', 'b', 'c', 'd']

(note, not hijacking the keyword list for a variable name)

you can walk through this in steps of two:

for i in range(0,len(L)-1,2):
  print(L[i]+L[i+1])

Use rstrip to remove characters o the right, for example L[i].rstrip('\n')

Comments

0

You could define a method which groups for you the elements in the list:

def group_by(iterable, n = 2):
  if len(iterable)%n != 0: raise Exception("Error: uneven grouping")
  # if n < 2: n = 1
  i, size = 0, len(iterable)
  while i < size-n+1:
    yield iterable[i:i+n]
    i += n

So for example if your list is:

words = ["a", "b", "c", "d"]
group_by(words, 2) #=> [['a', 'b'], ['c', 'd']]

Or you can group by 3:

words = ["a", "b", "c", "d", "e", "f"]
cons = group_by(words, 3) #=> [['a', 'b', 'c'], ['d', 'e', 'f']]

Then you can use in this way:

res = [ "".join(pair) for pair in group_by(words, 2) ] # maybe you want to add "\n" to the joined string
#=> ['ab', 'cd', 'ef']


The method throws an error if number of elements can not be evenly grouped:

words = ["a", "b", "c", "d", "e"]
cons = group_by(words, 2) #=> Exception: Error: uneven grouping

Comments

0

I'm sorry that I use most of the time numpy. So a solution can be:

li = ['a', 'b', 'c', 'd']
L = np.array(li)

a1 = np.char.array([L[0], L[2]])
a2 = np.char.array([L[1], L[3]])

a1 + a2

chararray(['ab', 'cd'], dtype='<U2')

Comments

0

You can also starmap zipped lists to the operator concat:

from operator import concat
from itertools import starmap

l = ["a", "b", "c", "d"]

z = zip(l[::2], l[1::2])

list(starmap(concat, z))
# ['ab', 'cd']

Comments

0

You could slice your list into the even elements and odd elements.

Let's say your list is called l

Even elements - l[::2]

Odd elements - l[1::2]

Then you could use a list comprehension to concatenate them after zipping. So:

[x + y for x, y in zip(l[::2], l[1::2])]

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.