Python 删除和重新插入空格

Python 删除和重新插入空格,python,string,Python,String,从文本中删除空格,然后在执行必要功能后重新插入先前删除的空格的最有效方法是什么 以下面的示例为例,下面是一个用于编码简单railfence密码的程序: from string import ascii_lowercase string = "Hello World Today" string = string.replace(" ", "").lower() print(string[::2] + string[1::2]) 这将产生以下结果: hlooltdyelwrdoa 这是因为它必

从文本中删除空格,然后在执行必要功能后重新插入先前删除的空格的最有效方法是什么

以下面的示例为例,下面是一个用于编码简单railfence密码的程序:

from string import ascii_lowercase

string = "Hello World Today"
string = string.replace(" ", "").lower()
print(string[::2] + string[1::2])
这将产生以下结果:

hlooltdyelwrdoa
这是因为它必须在编码文本之前删除间距。但是,如果现在要重新插入间距以使其保持不变:

hlool tdyel wrdoa

做这件事最有效的方法是什么?

正如其他一位评论者所提到的,您需要记录空格的来源,然后再将它们添加回去

from string import ascii_lowercase
string = "Hello World Today"
# Get list of spaces
spaces = [i for i,x in enumerate(string) if x == ' ']
string = string.replace(" ", "").lower()
# Set string with ciphered text
ciphered = (string[::2] + string[1::2])
# Reinsert spaces
for space in spaces:
    ciphered = ciphered[:space] + ' ' + ciphered[space:]

print(ciphered)

使用
list
join
操作

random_string = "Hello World Today"
space_position = [pos for pos, char in enumerate(random_string) if char == ' ']
random_string = random_string.replace(" ", "").lower()
random_string = list(random_string[::2] + random_string[1::2])

for index in space_position:
    random_string.insert(index, ' ')

random_string = ''.join(random_string)
print(random_string)

您可以使用
str.split
来帮助您。在空格上拆分时,剩余段的长度将告诉您拆分已处理字符串的位置:

broken = string.split(' ')
sizes = list(map(len, broken))
您需要大小的累计和:

from itertools import accumulate, chain
cs = accumulate(sizes)
现在可以恢复空间:

processed = ''.join(broken).lower()
processed = processed[::2] + processed[1::2]

chunks = [processed[index:size] for index, size in zip(chain([0], cs), sizes)]
result = ' '.join(chunks)

这个解决方案不是特别简单或高效,但它确实避免了显式循环。

我认为这可能会有所帮助

string = "Hello World Today"
nonSpaceyString = string.replace(" ", "").lower()
randomString = nonSpaceyString[::2] + nonSpaceyString[1::2]
spaceSet = [i for i, x in enumerate(string) if x == " "]
for index in spaceSet:
    randomString = randomString[:index] + " " + randomString[index:]
print(randomString)

您可以使用以下小而简单的代码创建一个新字符串:

请注意,这不使用任何库,这可能会使速度变慢,但不太容易混淆

def weird_string(string):                                 # get input value

    spaceless = ''.join([c for c in string if c != ' '])  # get spaceless version
    skipped = spaceless[::2] + spaceless[1::2]            # get new unique 'code'
    result = list(skipped)                                # get list of one letter strings

    for i in range(len(string)):                          # loop over strings
        if string[i] == ' ':                              # if a space 'was' here
            result.insert(i, ' ')                         # add the space back
    # end for

    s = ''.join(result)                                   # join the results back
    return s                                              # return the result

查找并记录所有空格的位置(例如,作为列表)。修改字符串后,在预先录制的位置插入空格。
def weird_string(string):                                 # get input value

    spaceless = ''.join([c for c in string if c != ' '])  # get spaceless version
    skipped = spaceless[::2] + spaceless[1::2]            # get new unique 'code'
    result = list(skipped)                                # get list of one letter strings

    for i in range(len(string)):                          # loop over strings
        if string[i] == ' ':                              # if a space 'was' here
            result.insert(i, ' ')                         # add the space back
    # end for

    s = ''.join(result)                                   # join the results back
    return s                                              # return the result