Quelle est la manière la plus efficace de supprimer des espaces d'un texte, puis après que la fonction nécessaire a été exécutée, réinsérez l'espacement précédemment supprimé?
Prenez cet exemple ci-dessous, voici un programme pour encoder un simple chiffrement railfence:
hlool tdyel wrdoa
Ceci génère ce qui suit:
hlooltdyelwrdoa
C'est parce qu'il doit supprimer l'espacement avant d'encoder le texte. Cependant, si je veux maintenant réinsérer l'espacement pour le faire:
from string import ascii_lowercase
string = "Hello World Today"
string = string.replace(" ", "").lower()
print(string[::2] + string[1::2])
Quelle est la manière la plus efficace de le faire?
6 Réponses :
Comme mentionné par l'un des autres commentateurs, vous devez enregistrer l'origine des espaces, puis les rajouter dans
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)
Utilisation de l'opération list et 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)
Vous pouvez utiliser str.split pour vous aider. Lorsque vous divisez sur des espaces, les longueurs des segments restants vous indiqueront où diviser la chaîne traitée:
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)
Vous aurez besoin de la somme cumulative des tailles:
from itertools import accumulate, chain cs = accumulate(sizes)
Vous pouvez maintenant rétablir les espaces:
broken = string.split(' ')
sizes = list(map(len, broken))
Cette solution n'est pas particulièrement simple ou efficace, mais elle évite les boucles explicites. P >
Je pense que cela pourrait aider
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)
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
Vous pouvez créer une nouvelle chaîne avec ce (genre de) code petit mais simple:
Notez que cela n'utilise aucune bibliothèque, ce qui peut rendre cela plus lent, mais moins déroutant.
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
Trouvez et enregistrez les positions de tous les espaces (par exemple, sous forme de liste). Après avoir modifié la chaîne, insérez les espaces dans les positions préenregistrées.