Shubham R
Shubham R

Reputation: 7644

change first letter of a word in python with all the letters in the alphabet and generate a list

I have a string say string = 'bcde'

What I want to do is replace the first letter from the string (i.e. b) and replace it doing iterations for each letter in the alphabet, till z.

Desired Output:

['acde', 'bcde', 'ccde', 'dcde', 'ecde', 'fcde', ..., 'zcde']

This is the code that I'm currently using, but I get the wrong output:

a = 'bcde'
a = list(a)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet = list(alphabet)
final = []
for n,i in enumerate(a):
    if i==b:
        a[i] = [alphabet[x] for x in alphabet ]
        final.append(a[i])

Upvotes: 2

Views: 2374

Answers (5)

FlipTack
FlipTack

Reputation: 423

All the solutions here are way too complicated / over the top, just use a simple list comprehension:

text = 'abcd'
final = [c + text[1:] for c in 'abcdefghijklmnopqrstvuwxyz']

If you need to use the alphabet multiple times, use import string and then string.ascii_lowercase.

Upvotes: 2

Setop
Setop

Reputation: 2490

Because one can always mispell alphabet :

s = 'bcde'
final = list(map(lambda x: chr(x + ord('a')) + s[1:], range(26)))

Upvotes: 1

sachsure
sachsure

Reputation: 886

this is all you need:

alphabet = 'abcdefghijklmnopqrstuvwxyz'

a='bcde'
new_list = []
for i in alphabet:
    new_list.append(i+a[1:])

Upvotes: 2

iFlo
iFlo

Reputation: 1484

It could be done really easily with list comprehension

a = 'bcde'
alphabet = 'abcdefghijklmnopqrstuvwxyz'
post_string = a[1:]
final = [letter+post_string for letter in alphabet]

Upvotes: 4

ettanany
ettanany

Reputation: 19806

Try the following:

s = 'bcde'
final = []
if s[0] == 'b':
    final = ['{}{}'.format(i, s[1:]) for i in 'abcdefghijklmnopqrstuvwxyz']
print(final)

Output:

>>> final
['acde', 'bcde', 'ccde', 'dcde', 'ecde', 'fcde', 'gcde', 'hcde', 'icde', 'jcde', 'kcde', 'lcde', 'mcde', 'ncde', 'ocde', 'pcde', 'qcde', 'rcde', 'scde', 'tcde', 'ucde', 'vcde', 'wcde', 'xcde', 'ycde', 'zcde']

Upvotes: 0

Related Questions