Convert a string into an integer of its ascii valu

2019-07-23 13:17发布

问题:

I am trying to write a function that takes a string txt and returns an int of that string's character's ascii numbers. It also takes a second argument, n, that is an int that specified the number of digits that each character should translate to. The default value of n is 3. n is always > 3 and the string input is always non-empty.

Example outputs:

string_to_number('fff')
102102102

string_to_number('ABBA', n = 4)
65006600660065

My current strategy is to split txt into its characters by converting it into a list. Then, I convert the characters into their ord values and append this to a new list. I then try to combine the elements in this new list into a number (e.g. I would go from ['102', '102', '102'] to ['102102102']. Then I try to convert the first element of this list (aka the only element), into an integer. My current code looks like this:

def string_to_number(txt, n=3):
    characters = list(txt)
    ord_values = []


for character in characters:
    ord_values.append(ord(character))

    joined_ord_values = ''.join(ord_values)
    final_number = int(joined_ord_values[0])

    return final_number

The issue is that I get a Type Error. I can write code that successfully returns the integer of a single-character string, however when it comes to ones that contain more than one character, I can't because of this type error. Is there any way of fixing this. Thank you, and apologies if this is quite long.

回答1:

Try this:

def string_to_number(text, n=3):
    return int(''.join('{:0>{}}'.format(ord(c), n) for c in text))

print(string_to_number('fff'))
print(string_to_number('ABBA', n=4))

Output:

102102102
65006600660065

Edit: without list comprehension, as OP asked in the comment

def string_to_number(text, n=3):
    l = []
    for c in text:
        l.append('{:0>{}}'.format(ord(c), n))
    return int(''.join(l))

Useful link(s):

  • string formatting in python: contains pretty much everything you need to know about string formatting in python


回答2:

The join method expects an array of strings, so you'll need to convert your ASCII codes into strings. This almost gets it done:

ord_values.append(str(ord(character)))

except that it doesn't respect your number-of-digits requirement.