Home > Software engineering >  Replacing spaces in one string with characters of other string
Replacing spaces in one string with characters of other string

Time:10-17

Say I have two strings, string1="A B C " and string2="abc". How do combine these two strings so string1 becomes "AaBbCc"? So basically I want all the spaces in string1 to be replaced by characters in string2. I tried using two for-loops like this:

string1="A B C "
string2="abc"

for char1 in string1:
    if char1==" ":
        for char2 in string2:
            string1.replace(char1,char2)
    else:
        pass
print(string1)

But that doesn't work. I'm fairly new to Python so could somebody help me? I use version Python3. Thank you in advance.

CodePudding user response:

string1 = "A B C "
string2 = "abc"

out, repl = '', list(string2)
for s in string1:
    out  = s if s != " " else repl.pop(0)

print(out) #AaBbCc

CodePudding user response:

You can use iter on String2 and replace ' ' with char in String2 like below:

>>> string1 = "A B C "
>>> string2 = "abc"
>>> itrStr2 = iter(string2)
>>> ''.join(st if st!=' ' else next(itrStr2) for st in string1)
'AaBbCc'

If maybe len in two String is different you can use itertools.cycle like below:

>>> from itertools import cycle
>>> string1 = "A B C A B C "
>>> string2 = "abc"
>>> itrStr2 = cycle(string2)
>>> ''.join(st if st!=' ' else next(itrStr2) for st in string1)
'AaBbCcAaBbCc'
  • Related