简体   繁体   中英

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:]))

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM