python - list indices must be integers, not str error -
with little function here, trying change 10 digit integer phone number word form. gives me error.
def getwordform(phone_num): cake=list(phone_num) print(cake) v in cake: if cake[v] == 0: cake[v] = "zero " elif cake[v] == 1: cake[v] = "one " elif cake[v] == 2: cake[v] = "two " elif cake[v] == 3: cake[v] = "three " elif cake[v] == 4: cake[v] = "four " elif cake[v] == 5: cake[v] = "five " elif cake[v] == 6: cake[v] = "six " elif cake[v] == 7: cake[v] = "seven " elif cake[v] == 8: cake[v] = "eight " elif cake[v] == 9: cake[v] = "nine "
thanks everyone.
you're iterating on list
of 1-character strings, , trying find out if list
's element @ string index equal integer. i'll demonstrate why that's near need replacing variables literals:
def getwordform('1234567890'): ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']=list('1234567890') print(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']) '1','2',etc. in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']: if cake['1'] == 0: cake['1'] = "zero "
you have index list
integers. characters in phone number (which happen represent integers) have nothing index - have '9'
@ index 3. aren't returning anything, function run (if could), end, , throw away.
do instead:
def getwordform(phone_num): numbers = {'0':'zero', '1':'one', '2':'two', '3':'three', '4':'four', '5':'five', '6':'six', '7':'seven', '8':'eight', '9':'nine'} return ' '.join(numbers[num] num in phone_num)
the result expected:
>>> getwordform('123') 'one 2 three'
Comments
Post a Comment