JMatth
JMatth

Reputation: 141

list comprehension with slicing (all versions of string formed by deleting 1 character)

I am creating a list of all versions of a string that can be made by deleting only one character using a comprehension. I am able to remove each character but not able to keep the other characters.

wrd = 'superstar'
list2 = [(wrd[:1-1] + wrd[:i+1]) for i in range(len(wrd))]
print(list2)

Upvotes: 0

Views: 3100

Answers (3)

rAntonioH
rAntonioH

Reputation: 149

Here's how to slice the 'wrd' superstar in a list comprehension:

wrd = 'superstar'

to remove each letter, you need to add the first part of the string to the second part that is leftover when you remove that character:

the first part of 'wrd' is everything up to i (your question has :1-1).

wrd[:i]

the second part of 'wrd' is everything from i+1 and onward to the end.

wrd[i+1:]

results:

list2 = [wrd[:i]+wrd[i+1:] for i in range(len(wrd))]
print(list2)

['uperstar', 'sperstar', 'suerstar', 'suprstar', 'supestar', 'supertar', 'supersar', 'superstr', 'supersta']

to delete more letters (like 2) at once in sequence, simply add to i in 'wrd':

list3 = [wrd[:i]+wrd[i+2:] for i in range(len(wrd))]
print(list3)

['perstar', 'serstar', 'surstar', 'supstar', 'supetar', 'superar', 'supersr', 'superst', 'supersta']

Upvotes: 0

jamylak
jamylak

Reputation: 133634

>>> from itertools import combinations
>>> wrd = 'superstar'
>>> [''.join(comb) for comb in combinations(wrd, len(wrd) - 1)]
['supersta', 'superstr', 'supersar', 'supertar', 'supestar', 'suprstar', 'suerstar', 'sperstar', 'uperstar']

Upvotes: 5

Chris
Chris

Reputation: 22963

Your list slicing is a bit off. To remove a single character from a position in a string, use the form string[:index] + string[index + 1:] instead of string[:index - 1] + string[:index + 1]:

>>> word = 'superstar'
>>> words = [word[:i] + word[i + 1:] for i in range(len(word))]
>>> words
['uperstar', 'sperstar', 'suerstar', 'suprstar', 'supestar', 'supertar', 'supersar', 'superstr', 'supersta']
>>> 

Upvotes: 9

Related Questions