Asked  6 Months ago    Answers:  5   Viewed   33 times

Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?

There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.

 Answers

46

Python's string format method can take a format spec.

>>> "{0:b}".format(37)
'100101'

Format spec docs for Python 2

Format spec docs for Python 3

Tuesday, June 1, 2021
 
drowneath
answered 6 Months ago
100

Try this approach using the newer str.format syntax:

line_new = '{:>12}  {:>12}  {:>12}'.format(word[0], word[1], word[2])

And here's how to do it using the old % syntax (useful for older versions of Python that don't support str.format):

line_new = '%12s  %12s  %12s' % (word[0], word[1], word[2])
Friday, June 4, 2021
 
Fredy
answered 6 Months ago
50

To get a date string with milliseconds (3 decimal places behind seconds), use this:

from datetime import datetime

print datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

>>>> OUTPUT >>>>
2020-05-04 10:18:32.926

Note: For Python3, print requires parentheses:

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
Tuesday, June 8, 2021
 
lewiguez
answered 6 Months ago
61

StringIO documentation:

Unlike the memory files implemented by the StringIO module, those provided by [cStringIO] are not able to accept Unicode strings that cannot be encoded as plain ASCII strings.

If possible, use StringIO instead of cStringIO.

Monday, August 9, 2021
 
Michal Charemza
answered 4 Months ago
80
integer = 2
hex_string = '0x{:02x}'.format(integer)

See pep 3101, especially Standard Format Specifiers for more info.

Saturday, November 6, 2021
 
CAMason
answered 3 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share