wkelly
wkelly

Reputation: 41

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

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

For example:

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

output = "ESTD TD L ATPNP ZQ EPIE"

Upvotes: 4

Views: 317

Answers (3)

Aaditya Ura
Aaditya Ura

Reputation: 12669

You can try insert 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

Upvotes: 0

Joe Iddon
Joe Iddon

Reputation: 20414

You need to iterate over the indexes and characters in string1 using enumerate().

On each iteration, if the character is a space, add a space to the output string (note that this is inefficient as you are creating a new object as strings are immutable), otherwise add the character in string2 at that index to the output string.

So that code would look like:

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

However, it would be more efficient to use a very similar method, but with a generator and then str.join. This removes the slow concatenations to the output string:

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))

Upvotes: 2

cs95
cs95

Reputation: 402343

Insert characters as appropriate into a placeholder list and concatenate it after using 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 efficient as it avoids repeated string concatenation.

Upvotes: 3

Related Questions