Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Using %x to format number to hex and number of digits

Reply
Thread Tools

Re: Using %x to format number to hex and number of digits

 
 
Chris Rebert
Guest
Posts: n/a
 
      11-05-2010
On Fri, Nov 5, 2010 at 11:23 AM, Matty Sarro <(E-Mail Removed)> wrote:
> I'm currently trying to convert a digit from decimal to hex, however I need
> the full 4 digit hex form. Python appears to be shortening the form.
> Example:
>
> num = 10
> num = "%x"%(num)
> print(num)
>
>>a

>
> num = 10
> num = "%#x"%(num)
> print(num)
>
>>0xa

>
> I need it to output as 0x0a, and the exercise is requiring me to use %x to
> format the string. Any help would be appreciated.


Use str.zfill() and add the 0x manually:

num = 10
hexdig = "%x" % num
padded = hexdig.zfill(2) # pad with 0 if necessary
oxd = "0x" + padded
print(oxd)

Cheers,
Chris
--
http://blog.rebertia.com
 
Reply With Quote
 
 
 
 
Grant Edwards
Guest
Posts: n/a
 
      11-05-2010
On Fri, Nov 5, 2010 at 11:23 AM, Matty Sarro <(E-Mail Removed)> wrote:
> I'm currently trying to convert a digit from decimal to hex, however I need
> the full 4 digit hex form. Python appears to be shortening the form.
> Example:
>
> num = 10
> num = "%x"%(num)
> print(num)
>
>>a

>
> num = 10
> num = "%#x"%(num)
> print(num)
>
>>0xa

>
> I need it to output as 0x0a, and the exercise is requiring me to use %x to
> format the string. Any help would be appreciated.


http://docs.python.org/release/2.5.2...q-strings.html

What you're asking for is called "zero padding", so if I were you, I'd
search the above page for the phrase "zero pad".

--
Grant Edwards grant.b.edwards Yow! BARBARA STANWYCK makes
at me nervous!!
gmail.com
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Using %x to format number to hex and number of digits Tim Chase Python 2 11-06-2010 01:22 AM
Hex Color Codes - Hex 6 <=> Hex 3 lucanos@gmail.com HTML 10 08-18-2005 11:21 PM
How to escape hex digits in a regular expression!!! aefxx Java 1 12-17-2004 10:12 PM
How to convert an hex string to a Hex number chirs Javascript 3 12-01-2003 10:06 PM
hex(-5) => Futurewarning: ugh, can't we have a better hex than '-'[:n<0]+hex(abs(n)) ?? Bengt Richter Python 6 08-19-2003 07:33 AM



Advertisments