1

How to join two or more strings in python with one character after another?

For example

a = 'hello'
b = 'world'

output = 'hweolellod'

Same goes for three or more strings. using + is not helping.

Noob Saibot
  • 113
  • 1
  • 7

2 Answers2

3

You could try this:

''.join([x + y for x, y in zip(a, b)])

which gives:

'hweolrllod'
Colin Ricardo
  • 16,488
  • 11
  • 47
  • 80
3

One way is to use str.join with itertools:

from itertools import chain, zip_longest

a = 'hello'
b = 'world'

zipper = zip_longest(a, b, fillvalue='')
res = ''.join(list(chain.from_iterable(zipper)))

print(res)

hweolrllod

Explanation

  • zip_longest is used to account for inconsistent length strings.
  • zipper here is a lazy iterator which iterates each character of a and b simultaneously by index.
  • List creation, while not necessary, is more efficient with str.join.
jpp
  • 159,742
  • 34
  • 281
  • 339