feefoo234
feefoo234

Reputation: 1

Python: Converting word to list of letters, then returning indexes of the letters against lower case alphabet

I have already completed the task but in its most basic form looking for help shortening it and so it can apply to any word not just one with eight letters, here's what I've got so far (bit long for what it does):

alpha = map(chr, range(97, 123))
word = "computer"
word_list = list(word)

one = word[0]
two = word[1]
three = word[2]
four = word[3]
five = word[4]
six = word[5]
seven = word[6]
eight = word[7]


one_index = str(alpha.index(one))
two_index = str(alpha.index(two))
three_index = str(alpha.index(three))
four_index = str(alpha.index(four))
five_index = str(alpha.index(five))
six_index = str(alpha.index(six))
seven_index = str(alpha.index(seven))
eight_index = str(alpha.index(eight))

print (one + "=" + one_index)
print (two + "=" + two_index)
print (three + "=" + three_index)
print (four + "=" + four_index)
print (five + "=" + five_index)
print (six + "=" + six_index)
print (seven + "=" + seven_index)
print (eight + "=" + eight_index)

Upvotes: 0

Views: 706

Answers (4)

feefoo234
feefoo234

Reputation: 1

thanks for the help managed to solve it myself in a different way using a function and a while loop, not as short but will work for all lower case words:

alpha = map(chr, range (97,123))
word = "computer"
count = 0
y = 0

def indexfinder (number):
     o = word[number]
     i = str(alpha.index(o))
     print (o + "=" + i)


while count < len(word):
    count = count + 1
    indexfinder (y)
    y = y+1

Upvotes: 0

chepner
chepner

Reputation: 532333

Start with a dict that maps each letter to its number.

import string
d = dict((c, ord(c)-ord('a')) for c in string.lowercase)

Then pair each letter of your string to the appropriate index.

result = [(c, d[c]) for c in word]

Upvotes: 0

Rahul K P
Rahul K P

Reputation: 16081

Use for loop for loop,

alpha = map(chr, range(97, 123))
word = "computer"
for l in word:
    print '{} = {}'.format(l,alpha.index(l.lower()))

Result

c = 2
o = 14
m = 12
p = 15
u = 20
t = 19
e = 4
r = 17

Upvotes: 0

Max Ploner
Max Ploner

Reputation: 31

What you are probably looking for is a for-loop.

Using a for-loop your code could look like this:

word = "computer"

for letter in word:
  index = ord(letter)-97
  if (index<0) or (index>25):
    print ("'{}' is not in the lowercase alphabet.".format(letter))
  else:
    print ("{}={}".format(letter, str(index+1))) # +1 to make a=1

If you use

for letter in word:
  #code

the following code will be executed for every letter in the word (or element in word if word is a list for example).

A good start to learn more about loops is here: https://en.wikibooks.org/wiki/Python_Programming/Loops

You can find tons of ressources in the internet covering this topic.

Upvotes: 2

Related Questions