4

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"
0

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

7 Comments

why .isspace()? very clever though :)
@JoeIddon cleaner than c == ' ' imo, and thank you. I like your generator solution, it was the first thing I came up with myself.
But in general, == is more extensible. Oh also, isn't the list-comp unnecessary as you can just use a generator if passing intostr.join.
@JoeIddon Ah, that's a common gotcha with str.join. It is faster to pass a list than a generator, because str.join will anyway make a second pass over it to create the list in memory. There is a source somewhere, I can find it.
@JoeIddon You may peruse this excellent answer by Raymond Hettinger.
|
2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.