Convert string to ASCII value python

后端 未结 8 1687
深忆病人
深忆病人 2020-12-07 22:43

How would you convert a string to ASCII values?

For example, \"hi\" would return 104105.

I can individually do ord(\'h\') and ord(\'i\'), but it\'s going to

相关标签:
8条回答
  • 2020-12-07 23:15

    You can use a list comprehension:

    >>> s = 'hi'
    >>> [ord(c) for c in s]
    [104, 105]
    
    0 讨论(0)
  • 2020-12-07 23:17

    your description is rather confusing; directly concatenating the decimal values doesn't seem useful in most contexts. the following code will cast each letter to an 8-bit character, and THEN concatenate. this is how standard ASCII encoding works

    def ASCII(s):
        x = 0
        for i in xrange(len(s)):
            x += ord(s[i])*2**(8 * (len(s) - i - 1))
        return x
    
    0 讨论(0)
提交回复
热议问题