Domanda

I've got string like x='0x08h, 0x0ah' in Python, wanting to convert it to [8,10] (like unsigned ints). I could split and index it like [int(a[-3:-1],16) for a in x.split(', ')] but is there a better way to convert it to a list of ints?

Would it matter if I had y='080a'?

edit (for plus points:).) what (sane) string-based hexadecimal notations have python support, and which not?

È stato utile?

Soluzione

You really have to know what the pattern you're trying to parse is, before you write a parser.

But it looks like your pattern is: optional 0x, then hex digits, then optional h. At least that's the most reasonable thing I can come up with that handles both '0x08h' and '080a'. So:

def parse_hex(s):
    return int(s.lstrip('0x').rstrip('h'), 16)

Then:

numbers = [parse_hex(s) for s in x.split(', ')]

Of course you don't actually need to remove the 0x prefix, because Python accepts that as part of a hex string, so you could write it as:

def parse_hex(s):
    return int(s.rstrip('h'), 16)

However, I think the intention is clearer if you're more explicit.


From your edit:

edit what (sane) string-based hexadecimal notations have python support, and which not?

See the documentation for int:

Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code.

That's it. (If you read the rest of the paragraph, if you're guaranteed to have 0x/0X, you don't have to explicitly use base=16. But that doesn't help you here, so that one sentence is really all you need.) The docs on Numeric Types and Numeric literals detail exactly what "as with integer literals in code"; the only thing surprising there is that negative numbers aren't literals, complex numbers aren't literals (but pure imaginary numbers are), and non-ASCII digits can be used but the documentation doesn't explain how.

Altri suggerimenti

You can also use map: map(lambda s:int(s.lower().replace('0x','').replace('h',''), 16),x.split(', '))

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top