删除和重新插入空间

时间:2019-01-04 03:45:09

标签: python string

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

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

from string import ascii_lowercase

string = "Hello World Today"
string = string.replace(" ", "").lower()
print(string[::2] + string[1::2])

这将输出以下内容:

hlooltdyelwrdoa

这是因为它必须在编码文本之前删除空格。但是,如果我现在想重新插入间距以使其:

hlool tdyel wrdoa

最有效的方法是什么?

6 个答案:

答案 0 :(得分:2)

正如其他评论者之一提到的那样,您需要记录空格的来源,然后将其重新添加到

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)

答案 1 :(得分:1)

使用listjoin操作,

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)

答案 2 :(得分:1)

您可以使用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)

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

答案 3 :(得分:1)

我认为这可能有帮助

  string =“今天的世界您好”
nonSpaceyString = string.replace(“”,“”).lower()
randomString = nonSpaceyString [:: 2] + nonSpaceyString [1 :: 2]
spaceSet = [i对于i,如果x ==“”,则x在枚举(string)中]
用于spaceSet中的索引:
    randomString = randomString [:index] +“” + randomString [index:]
打印(randomString)
 

答案 4 :(得分:0)

string = "Hello World Today"
# getting index of ' ' 
index = [i for i in range(len(string)) if string[i]==' ']
# storing the non ' ' characters
data = [i for i in string.lower() if i!=' ']
#  applying cipher code as mention in OP STATEMENT
result  = data[::2]+data[1::2]
# inserting back the spaces in there position as they had in original string 

for i in index:
    result.insert(i, ' ')
# creating a string solution 
solution = ''.join(result)
print(solution)

# output hlool tdyel wrdoa

答案 5 :(得分:0)

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

请注意,它不使用任何库,这可能会使速度变慢,但减少混乱。

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