ProjectPokket ProjectPokket - 1 month ago 7
Python Question

Change Letters to numbers (ints) in python

This might be python 101, but I am having a hard time changing letters into a valid integer.

The put what I am trying to do simply

char >> [ ] >> int

I created a case statement to give me a number depending on certain characters, so what I tried doing was

def char_to_int(sometext):
return {
'Z':1,
'Y':17,
'X':8,
'w':4,
}.get(sometext, '')


Which converts the letter into a number, but when I try using that number into any argument that takes ints it doesn't work.

I've tried

text_number = int(sometext)


But I get the message TypeError: int() argument must be a string or a number, not 'function'

So from there I returned the type of sometext using

print(type(sometext))


And the return type is a function.

So my question is, is there a better way to convert letters into numbers, or a better way to setup my switch/def statement

Heres the full code where its call

if sometext:
for i in range ( 0, len(sometext)):
char_to_int(sometext[i])

I've managed to get it working, ultimately what I changed was the default of the definition, I now set the definition to a variable before instead of calling it in another function, and I recoded the section I was using it.

Originally my definition looked liked this

def char_to_int(sometext):
return {
...
}.get(sometext, '')


But I changed the default to 0, so now it looks like

def char_to_int(sometext):
return {
...
}.get(sometext, 0)


The old code that called the definition looked

if sometext:
for i in range ( 0, len(sometext)):
C_T_I = int(char_to_int(sometext[i]))


I changed it to this.

if sometext:
for i in range ( 0, len(sometext)):
C_T_I = char_to_int(sometext[i])
TEXTNUM = int(C_T_I)


Hopefully this clarifies the changes. Thanks for everyone's assistance.

Answer

in the python console:

>>> type({ 'Z':1, 'Y':17, 'X':8, 'w':4, }.get('X', '')) <class 'int'>

so as cdarke suggested, you should look at how you are calling the function.