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

时间:2018-03-25 20:32:24

标签: python string python-3.x

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"

3 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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))

答案 2 :(得分:0)

您可以尝试插入方法:

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