pythonrecursionord

Using ord() recursively in Python


I need to convert a string to numbers using a recursive function and I'm a little confused about how to go around the base and recursive cases. I have the following code but I'm not sure where it's going wrong.

def string_to_num(s):
    if s == "":
        return []
    else:
        return ord(s[0]) + string_to_num(ord(s[1:]))

Solution

  • You need assume string_to_num(ord(s[1:])) back ord as string so you don't need ord(s[1:]) you need string_to_num(s[1:]) and you need back string then use +, you can change your code like below:

    >>> def string_to_num(s):
    ...    if s == '':
    ...        return ''
    ...    return f'{ord(s[0])}' + string_to_num(s[1:])
    
    >>> string_to_num('abc')
    '979899'
    

    And if you want as list you can use this:

    >>> def string_to_num(s):
    ...    if s == '':
    ...        return []
    ...    return [ord(s[0])] + string_to_num(s[1:])
    
    >>> string_to_num('abc')
    [97, 98, 99]