Question

I am currently trying to make a Caesar decoder, so I am trying to find out how to take user input of the value of the shift, and using that input to shift each item in a list. But each time I try, it just keeps giving me an error.

For example:

word in the ASCII would be:

[119, 111, 114, 100]

If the given input of shift was 2, I would want the list to be:

[121, 113, 116, 102]

Please help. This is my first time programming and this Caesar Decoder is driving me crazy :(

This is what I have so far

import string

def main():

    inString = raw_input("Please enter the word to be "
                        "translated: ")
    key = raw_input("What is the key value or the shift? ")

    toConv = [ord(i) for i in inString] # now want to shift it by key value
    #toConv = [x+key for x in toConv]   # this is not working, error gives 'cannot add int and str

    print "This is toConv", toConv

Also, it would be helpful if you guys don't use any fancy functions. Instead, please use the existing code. I am a newbie.

Was it helpful?

Solution

raw_input returns a string object and ord returns an integer. Moreover, as the error message states, you cannot add strings and integers together with +:

>>> 'a' + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>>

However, that is exactly what you are trying to do here:

toConv = [x+key for x in toConv]

In the above code, x will be an integer (because toConv is a list of integers) and key will be a string (because you used raw_input to get its value).


You can fix the problem by simply converting the input into an integer:

key = int(raw_input("What is the key value or the shift? "))

Afterwards, your list comprehension will work as it should.


Below is a demonstration:

>>> def main():
...     inString = raw_input("Please enter the word to be "
...                         "translated: ")
...     # Make the input an integer
...     key = int(raw_input("What is the key value or the shift? "))
...     toConv = [ord(i) for i in inString]
...     toConv = [x+key for x in toConv]
...     print "This is toConv", toConv
...
>>> main()
Please enter the word to be translated: word
What is the key value or the shift? 2
This is toConv [121, 113, 116, 102]
>>>

OTHER TIPS

If you are interested in a one liner:

shifted_word = "".join([chr(ord(letter)+shift_value) for letter in word])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top