Jordan M
Jordan M

Reputation: 19

Create all possible words, by inserting character into existing string

New to python/programming. I'm trying to create a list of every possible word by inserting a character into a given string.

e.g.

'thx' = ['athx','tahx','thax','thxa']

I can accomplish this by splitting my loop with if/else, but i'm trying to solve without it - I can't seem to find a way that will add the character to both the very beginning and very end. (both athx & thxa)

From looking into this, it appears the only way would be with a regular expression. But, I'm not there yet. Really just trying to make sure I'm not missing anything on a more fundamental level.

Upvotes: 0

Views: 74

Answers (1)

Kenan Banks
Kenan Banks

Reputation: 212010

This works:

>>> w = 'thx'
>>> letter = 'a'
>>> words = [w[:i] + letter + w[i:] for i in range(len(w) + 1)]
>>> words 
['athx', 'tahx', 'thax', 'thxa']

Upvotes: 6

Related Questions