Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can a list be converted to an integer

I am trying to write a program to convert a message inta a secret code. I m trying to create a basic code to work up from. here is the problem.

data = input('statement')
for line in data:
    code = ('l' == '1',
            'a' == '2'
            'r' == '3',
            'y' == '4')
    line = line.replace(data, code, [data])
print(line)    

this point of the above progam is so when i input my name:

larry

the output should be

12334

but I continue to recieve this message

TypeError: 'list' object cannot be interpreted as an integer

so i assumed this meant that my code variable must be an integer to be used in replace() is there a way to convert that string into an integer or is there another way to fix this?

like image 281
derpyherp Avatar asked Feb 17 '23 08:02

derpyherp


1 Answers

The reason why your original code gave you the error is because of line.replace(data, code, [data]). The str.replace method can take 3 arguments. The first is the string you want to replace, the second is the replacement string, and the third, optional argument is how many instances of the string you want to replace - an integer. You were passing a list as the third argument.

However, there are other problems to your code as well.

code is currently (False, False, False, False). What you need is a dictionary. You might also want to assign it outside of the loop, so you don't evaluate it every iteration.

code = {'l': '1', 'a': '2', 'r': '3', 'y': '4'}

Then, change your loop to this:

data = ''.join(code[i] for i in data)

print(data) gives you the desired output.

Note however that if a letter in the input isn't in the dictionary, you'll get an error. You can use the dict.get method to supply a default value if the key isn't in the dictionary.

data = ''.join(code.get(i, ' ') for i in data)

Where the second argument to code.get specifies the default value.

So your code should look like this:

code = {'l': '1', 'a': '2', 'r': '3', 'y': '4'}

data = input()
data = ''.join(code.get(i, ' ') for i in data)

print(data)
like image 135
Volatility Avatar answered Feb 27 '23 11:02

Volatility