简体   繁体   中英

perl hex() analog in python

perl hex() analog in python how to?
I have next perl code:

my $Lon = substr($Hexline,16,8);
say $output_f "Lon: " . hex($Lon) . "";

where $Hexline has "6a48f82d8e828ce82b82..." format

I try it on python

Lon = int(Hexline[16:24], 16)
f.write('lon = %s' % str(Lon)+'\n')

is it right?

EDIT: in perl's case hex() gives me a decimal value.

Yes, to convert an hexadecimal string to an integer you use int(hex_str, 16) .

Note that in your write method call:

  • You don't need to concatenate two strings to add the new line character, you can add it to the formatting string directly.
  • To print integer you should use %d instead of %s .
  • You don't really need to call str to transform the integer into a string.

Hence, the write call could be written as:

f.write('lon = %d\n' % Lon)

Alternatively, you could also use format this way:

f.write('lon = {0}\n'.format(Lon))

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