Reputation: 1
This is the assignment: Write a program that gets a single word from the user. For each letter in the word, print the index of that letter in the string 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' (e.g., 'A' would print 0, 'z' would print 51). Print all the indices on one line, separated by spaces.
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
word = input('Type a word: ')
for ind in word:
answer = ind.index(alphabet[0,-1])
print(answer)
My code does not run. It says "TypeError: string indices must be integers". 0 and -1 are both integers, and they indicate the first and last positions of a given string. I don't understand why this is not running properly. The code should take alphabet at position 0, see that there is no matching value in word, and then move on to the next one until it reaches the first character's position in the typed string. It should then print out that number, and keep going. What am I doing wrong?
Upvotes: 0
Views: 6530
Reputation: 316
Or you could just use ASCII codes using the ord()
function,
word = input("word:")
for i in range(len(word)):
print(ord(word[i:i+1]), end="")
This will give you a number output from a string and its not just limited to the alphabet
Upvotes: 0
Reputation: 2662
I think you meaning to be following a pattern like this. Get a each character from the input word and find the index in alphabet where the character occurs.
answer = []
for char in word:
answer += [alphabet.index(char)]
You can further simplify with a list comprehension
answer = [alphabet.index(char) for char in word]
Upvotes: 1
Reputation: 33351
You're calling index
the wrong way. You need to swap the arguments:
answer = alphabet.index(ind)
Upvotes: 1