Home > OS >  How do I manipulate my string to insert individual characters of another string in Python?
How do I manipulate my string to insert individual characters of another string in Python?

Time:03-03

I want to insert each character from one string, let's call it string A, into every other slot in another string, let's call it string B.

So, for example:

stringA = "abcde"
stringB = "1234"

output = "a1b2c3d4e"

where the length of string B is always one less than the length of string A.

I was thinking of using slices (since Python strings are immutable) and doing something like:

for i in range(0, len(stringA)):
  stringA = stringA[i]   stringB[i]   stringA[i 1 : len(stringA)]

But I'm painfully aware that every time I add something to string A, all the indexes change. Is there a string method that I don't know about that'll help me do this? By the way, this is in Python 3, and there is possible repetition of characters in string B, but not in string A. E.g. string A could be "abcde" and string B could be "1212".

CodePudding user response:

You can use itertools.zip_longest to pair them up with a fillvalue of an empty string and then join those together with an empty string, eg:

from itertools import zip_longest

output = ''.join(''.join(pair) for pair in zip_longest(stringA, stringB, fillvalue=''))

Gives you:

'a1b2c3d4e'

CodePudding user response:

zip() the strings, join the resulting tuples, pad with the leftover of the longest string:

''.join(sum(zip(stringA, stringB), ())) \
    stringA[len(stringB):] \
    stringB[len(stringA):]
#'a1b2c3d4e'

CodePudding user response:

I don't have the reputation to comment, but if you want to jump down the rabbit hole: Most pythonic way to interleave two strings ;)

  • Related