How to copy spaces from one line to another in Python?

I need a way to copy all the space positions of one row to another row that has no spaces.

For instance:

string1 = "This is a piece of text"
string2 = "ESTDTDLATPNPZQEPIE"

output = "ESTD TD L ATPNP ZQ EPIE"
+4
source share
3 answers

Insert the appropriate characters into the note list and put it together after use str.join.

it = iter(string2)
output = ''.join(
    [next(it) if not c.isspace() else ' ' for c in string1]  
)

print(output)
'ESTD TD L ATPNP ZQ EPIE'

This is effective because it avoids the repeated concatenation of strings.

+3
source

You need to iterate over indices and characters in string1with enumerate().

, - , ( , , , ), string2 index .

, :

output = ''
si = 0
for i, c in enumerate(string1):
    if c == ' ':
         si += 1
         output += ' '
    else:
         output += string2[i - si]

, , str.join. :

def chars(s1, s2):
    si = 0
    for i, c in enumerate(s1):
        if c == ' ':
            si += 1
            yield ' '
        else:
            yield s2[i - si]
output = ''.join(char(string1, string2))
+2

You can try to insert a method:

string1 = "This is a piece of text"
string2 = "ESTDTDLATPNPZQEPIE"


string3=list(string2)

for j,i in enumerate(string1):
    if i==' ':
        string3.insert(j,' ')
print("".join(string3))

Outout:

ESTD TD L ATPNP ZQ EPIE
0
source

Source: https://habr.com/ru/post/1695316/


All Articles