简体   繁体   中英

Replacing spaces in one string with characters of other string

Say I have two strings, string1="ABC " 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.

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM