Python

 

 

 

 

Python - Number Manipulation 

 

In the realm of computer programming, working with numbers is an integral part of almost every task you'll encounter. From solving mathematical problems to processing data and handling user input, number manipulation is essential to building efficient and effective applications. Python, a powerful and versatile programming language, provides a wealth of functions to perform various number conversions and manipulations, making it an ideal choice for developers across all skill levels.

 

In this comprehensive guide, we'll explore the different ways you can manipulate numbers in Python, focusing on key techniques and built-in functions that you can easily integrate into your projects. Whether you're a beginner looking to learn the ropes or a seasoned programmer seeking to expand your knowledge, this note will help you gain a deeper understanding of number manipulation in Python.

 

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

 

 

 

Convert a number to a string  

 

In Python, converting a number to a string is a common operation, especially when dealing with user input or displaying results. The str() function is used to perform this conversion, allowing you to change any number, whether it's an integer, a long integer, or a number in hexadecimal or binary format, into a string. This is particularly useful when you need to concatenate a number with a string or format it for output.

 

 

< Example 1 >

 

print("str(123)=",str(123))

print("str(12345678901234567890)=",str(12345678901234567890))

print("str(0xA)=",str(0xA))

print("str(0xAB)=",str(0xAB))

print("str(0xABC)=",str(0xABC))

print("str(0b1)=",str(0b1))

print("str(0b0111)=",str(0b0111))

print("str(0b11111111)=",str(0b11111111))

 

 

Result :----------------------------------

str(123)= 123

str(12345678901234567890)= 12345678901234567890

str(0xA)= 10

str(0xAB)= 171

str(0xABC)= 2748

str(0b1)= 1

str(0b0111)= 7

str(0b11111111)= 255

 

 

 

Convert Hex String to Integer

 

Converting a hexadecimal string to an integer is a common operation when dealing with numbers in various formats. In Python, you can use the int() function to perform this conversion, providing the hexadecimal string and specifying the base as 16 or you can use str() function to covert the Hex to a string in decimal format.

 

 

< Example 1 >

 

>>> str(0xABC)

 

'2748'

 

 

< Example 2 >

 

>>> str(0xabc)

 

'2748'

 

 

< Example 3 >

 

# If you put the hex number in string format, it does str() does not convert it into integer

>>> str('0xABC')   

 

'0xABC'

 

 

< Example 4 >

 

>>> int('0xABC',16)

 

2748

 

 

 

Convert an Integer to Hex String

 

Converting an integer to a hexadecimal string is a useful operation when you need to represent numbers in a different base or format for certain tasks, such as working with color codes, memory addresses, or other applications that require hexadecimal representation. In Python, you can use the hex() function to convert an integer to a hexadecimal string.

 

 

< Example 1 >

 

>>> hex(2748)

 

'0xabc'

 

 

 

Convert an Integer to Binary String

 

Converting an integer to a binary string is an important operation when you need to work with numbers in binary format, which is the base-2 numeral system used in digital electronics and computing. Python provides the bin() function to easily convert integers into binary strings. or you can use .format() function to print the number in the specified binary format

 

 

< Example 1 >

 

>>> bin(2748)

 

'0b101010111100'

 

 

< Example 2 >

 

>>> bin(2748)[2:]

 

'101010111100'

 

 

< Example 3 >

 

>>> '{0:016b}'.format(2748)

 

'0000101010111100'

 

 

 

Convert a Binary String to an Integer

 

Converting a binary string to an integer is a common operation when working with numbers in different formats, especially when you need to perform calculations or manipulations that require integer values. In Python, you can use the int() function to convert a binary string to an integer, providing the binary string and specifying the base as 2. or you can use str() function to convert a binary number to integer string.

 

 

< Example 1 >

 

>>> int('0b101010111100',2)

 

2748

 

 

< Example 2 >

 

>>> str(0b101010111100)

 

'2748'

 

 

 

Convert a ASCII character into a Byte Array

 

Converting an ASCII character into a byte array is a useful operation when you need to work with the individual bytes that represent characters in a string, particularly for tasks such as data processing, communication, or encryption. In Python, you can use the bytearray() function along with the encode() method to convert a string containing ASCII characters into a byte array.

 

 

< Example 1 >

 

numStr = "123ABCDEF"

bArray = bytearray(numStr.encode('ascii'))

print(bArray)

 

for b in numStr :

   print("elements in numStr :", b)

 

for b in bArray :

   print("elements in bArray :", b)

 

 

Result :----------------------------------

bytearray(b'123ABCDEF')

elements in numStr : 1

elements in numStr : 2

elements in numStr : 3

elements in numStr : A

elements in numStr : B

elements in numStr : C

elements in numStr : D

elements in numStr : E

elements in numStr : F

elements in bArray : 49

elements in bArray : 50

elements in bArray : 51

elements in bArray : 65

elements in bArray : 66

elements in bArray : 67

elements in bArray : 68

elements in bArray : 69

elements in bArray : 70

 

 

 

Convert a Hex String into a stream of Hex Numbers (binascii package)

 

Converting a hex string into a stream of hex numbers is a useful operation when you need to work with raw binary data represented as a hexadecimal string. In Python, the binascii package provides a convenient function called a2b_hex() to perform this conversion.

 

 

< Example 1 >

 

import binascii

 

hexStr = "AABBCC"

hexNumbers = binascii.a2b_hex(hexStr)

 

print("hexStr = ",hexStr)

print("hexNumbers = ", hexNumbers)

 

Result :----------------------------------

hexStr =  AABBCC

hexNumbers =  b'\xaa\xbb\xcc'

 

 

 

Convert a stream of Hex Numbers into a Byte Array (bytearray,binascii)

 

Converting a stream of hex numbers into a byte array is a useful operation when you need to work with binary data in a mutable and iterable format. In Python, this can be achieved using the bytearray() function in conjunction with the binascii package.

 

 

< Example 1 >

 

import binascii

 

hexStr = "AABBCC"

hexNumbers = binascii.a2b_hex(hexStr)

byteArray = bytearray(hexNumbers)

 

print("hexStr = ",hexStr)

print("hexNumbers = ", hexNumbers)

print("byteArray = ", byteArray)

print("hexStr[0]=",hexStr[0])

print("hexNumbers[0]=",hexNumbers[0])

print("byteArray[0]=",byteArray[0])

 

Result :----------------------------------

hexStr =  AABBCC

hexNumbers =  b'\xaa\xbb\xcc'

byteArray =  bytearray(b'\xaa\xbb\xcc')

hexStr[0]= A

hexNumbers[0]= 170

byteArray[0]= 170

 

 

 

Convert a ByteArray into a String of Hex Numbers (bytearray,binascii)

 

Converting a byte array into a string of hex numbers is a useful operation when you need to represent binary data as a human-readable hexadecimal string. In Python, you can use the binascii package and its b2a_hex() function to perform this conversion

 

 

< Example 1 >

 

import binascii

 

ByteAry = b'\x45\x00\x00\x16\x36\xdd\x00\x00\x80\xfd\xfe\xa7\x01\x01\x01\x64\x01\x01\x01\x01\x48\x69'

HexStr=binascii.b2a_hex(ByteAry)

 

print("Byte Array = ",ByteAry)

print("Hex String = ",HexStr)

print("Ascii String = ",HexStr.decode('ascii'))

 

Result :----------------------------------

 

Byte Array =  b'E\x00\x00\x166\xdd\x00\x00\x80\xfd\xfe\xa7\x01\x01\x01d\x01\x01\x01\x01Hi'

Hex String =  b'4500001636dd000080fdfea701010164010101014869'

Ascii String =  4500001636dd000080fdfea701010164010101014869

 

 

 

Convert a ByteArray into a Long Integer and convert it into Binary

 

Converting a byte array into a long integer and then into binary is a useful operation when you need to manipulate or analyze binary data as an integer value. In Python, you can achieve this by using the int.from_bytes() method and string formatting.

 

 

< Example 1 >

 

import binascii

 

ByteAry = b'\x45\x00\x00\x16\x36'

BigInteger = int.from_bytes(ByteAry[0:len(ByteAry)], 'big')

BigBinary = '{0:0{1}b}'.format(BigInteger,len(ByteAry*8))

 

print("Byte Array = ",ByteAry)

print("BigInteger = ",BigInteger)

print("BigInteger (Hex) = ",'{0:X}'.format(BigInteger))

print("BigBinary = ",BigBinary)

 

Result :----------------------------------

 

Byte Array =  b'E\x00\x00\x166'

Big Integer =  296352749110

Big Integer (Hex) =  4500001636

BigBinary =  0100010100000000000000000001011000110110

 

 

 

Convert a ByteArray into a Long Integer and convert it into Binary and Back to Integer

 

Converting a byte array into a long integer, then into binary, and finally back to a long integer demonstrates the ability to work with binary data in various formats and perform calculations or manipulations based on the specific requirements of your application.

 

 

< Example 1 >

 

import binascii

 

ByteAry = b'\x45\x00\x00\x16\x36'

BigInteger = int.from_bytes(ByteAry[0:len(ByteAry)], 'big')

BigBinary = '{0:0{1}b}'.format(BigInteger,len(ByteAry*8))

BigIntFromBinary = int(BigBinary,2)

 

print("Byte Array = ",ByteAry)

print("BigInteger = ",BigInteger)

print("BigInteger (Hex) = ",'{0:X}'.format(BigInteger))

print("BigBinary = ",BigBinary)

print("BigIntFromBinary = ",BigIntFromBinary)

print("BigIntFromBinary (Hex) = ",'{0:X}'.format(BigIntFromBinary))

 

Result :----------------------------------

 

Byte Array =  b'E\x00\x00\x166'

BigInteger =  296352749110

BigInteger (Hex) =  4500001636

BigBinary =  0100010100000000000000000001011000110110

BigIntFromBinary =  296352749110

BigIntFromBinary (Hex) =  4500001636

 

 

 

Formating a Number - '{format}'.format(number)

 

Formatting a number using the '{format}'.format(number) method is a convenient way to control the appearance of numbers in your output. This method allows you to specify various formatting options, such as the number of digits, padding, and alignment.

 

 

< Example 1 >

 

print("Decimal Format=================================")

print("'{:d}'.format(123)=",'{:d}'.format(123))

print("'{:8d}'.format(123)=",'{:8d}'.format(123))

print("'{:08d}'.format(123)=",'{:08d}'.format(123))

print("'{0:d}'.format(123)=",'{0:d}'.format(123))

print("'{0:8d}'.format(123)=",'{0:8d}'.format(123))

print("'{0:08d}'.format(123)=",'{0:08d}'.format(123))

 

print("Float Format===================================")

print("'{:f}'.format(123)=",'{:f}'.format(123))

print("'{:5.1f}'.format(123)=",'{:5.1f}'.format(123))

print("'{:8.5f}'.format(123)=",'{:8.5f}'.format(123))

print("'{:10.5f}'.format(123)=",'{:10.5f}'.format(123))

print("'{:010.5f}'.format(123)=",'{:010.5f}'.format(123))

 

print("Hex Format====================================")

print("'{:x}'.format(123)=",'{:x}'.format(123))

print("'{:8x}'.format(123)=",'{:8x}'.format(123))

print("'{:08x}'.format(123)=",'{:08x}'.format(123))

print("'{:#08x}'.format(123)=",'{:#08x}'.format(123))

print("'{0:x}'.format(123)=",'{0:x}'.format(123))

print("'{0:8x}'.format(123)=",'{0:8x}'.format(123))

print("'{0:08x}'.format(123)=",'{0:08x}'.format(123))

print("'{0:#08x}'.format(123)=",'{0:#08x}'.format(123))

 

print("'{:X}'.format(123)=",'{:X}'.format(123))

print("'{:8X}'.format(123)=",'{:8X}'.format(123))

print("'{:08X}'.format(123)=",'{:08X}'.format(123))

print("'{:#08X}'.format(123)=",'{:#08X}'.format(123))

print("'{0:X}'.format(123)=",'{0:X}'.format(123))

print("'{0:8X}'.format(123)=",'{0:8X}'.format(123))

print("'{0:08X}'.format(123)=",'{0:08X}'.format(123))

print("'{0:#08X}'.format(123)=",'{0:#08X}'.format(123))

 

print("Binary Format==================================")

print("'{:b}'.format(123)=",'{:b}'.format(123))

print("'{:16b}'.format(123)=",'{:16b}'.format(123))

print("'{:016b}'.format(123)=",'{:016b}'.format(123))

print("'{:#016b}'.format(123)=",'{:#016b}'.format(123))

 

print("Format with digit specification ===============")

print("#{1} means the second argument in format() which is 8 in this example")

print("'{0:{1}d}'.format(123,8)=",'{0:{1}d}'.format(123,8))

print("#{1} means the second argument in format() which is 16 in this example")

print("'{0:{1}d}'.format(123.16)=",'{0:{1}d}'.format(123,16))

print("#{1} means the second argument in format() which is 8 in this example")

print("'{0:{1}b}'.format(123,8)=",'{0:{1}b}'.format(123,8))

print("#{1} means the second argument in format() which is 16 in this example")

print("'{0:{1}b}'.format(123.16)=",'{0:{1}b}'.format(123,16))

 

print("Format with digit and base specification ======")

print("#{1} means the second argument in format() which is 8 in this example")

print("#{2} means the third argument in format() which is 'd' in this example")

print("'{0:{1}{2}}'.format(123,8)=",'{0:{1}{2}}'.format(123,8,'d'))

print("#{1} means the second argument in format() which is 16 in this example")

print("#{2} means the third argument in format() which is 'd' in this example")

print("'{0:{1}{2}}'.format(123.16)=",'{0:{1}{2}}'.format(123,16,'d'))

print("#{1} means the second argument in format() which is 16 in this example")

print("#{2} means the third argument in format() which is 'd' in this example")

print("'{0:0{1}{2}}'.format(123.16)=",'{0:0{1}{2}}'.format(123,16,'d'))

print("#{1} means the second argument in format() which is 8 in this example")

print("#{2} means the third argument in format() which is 'b' in this example")

print("'{0:{1}{2}}'.format(123,8)=",'{0:{1}{2}}'.format(123,8,'b'))

print("#{1} means the second argument in format() which is 16 in this example")

print("#{2} means the third argument in format() which is 'b' in this example")

print("'{0:{1}{2}}'.format(123.16)=",'{0:{1}{2}}'.format(123,16,'b'))

print("#{1} means the second argument in format() which is 16 in this example")

print("#{2} means the third argument in format() which is 'b' in this example")

print("'{0:0{1}{2}}'.format(123.16)=",'{0:0{1}{2}}'.format(123,16,'b'))

 

 

Result :----------------------------------

Decimal Format=================================

'{:d}'.format(123)= 123

'{:8d}'.format(123)=      123

'{:08d}'.format(123)= 00000123

'{0:d}'.format(123)= 123

'{0:8d}'.format(123)=      123

'{0:08d}'.format(123)= 00000123

Float Format===================================

'{:f}'.format(123)= 123.000000

'{:5.1f}'.format(123)= 123.0

'{:8.5f}'.format(123)= 123.00000

'{:10.5f}'.format(123)=  123.00000

'{:010.5f}'.format(123)= 0123.00000

Hex Format====================================

'{:x}'.format(123)= 7b

'{:8x}'.format(123)=       7b

'{:08x}'.format(123)= 0000007b

'{:#08x}'.format(123)= 0x00007b

'{0:x}'.format(123)= 7b

'{0:8x}'.format(123)=       7b

'{0:08x}'.format(123)= 0000007b

'{0:#08x}'.format(123)= 0x00007b

'{:X}'.format(123)= 7B

'{:8X}'.format(123)=       7B

'{:08X}'.format(123)= 0000007B

'{:#08X}'.format(123)= 0X00007B

'{0:X}'.format(123)= 7B

'{0:8X}'.format(123)=       7B

'{0:08X}'.format(123)= 0000007B

'{0:#08X}'.format(123)= 0X00007B

Binary Format==================================

'{:b}'.format(123)= 1111011

'{:16b}'.format(123)=          1111011

'{:016b}'.format(123)= 0000000001111011

'{:#016b}'.format(123)= 0b00000001111011

Format with digit specification ===============

#{1} means the second argument in format() which is 8 in this example

'{0:{1}d}'.format(123,8)=      123

#{1} means the second argument in format() which is 16 in this example

'{0:{1}d}'.format(123.16)=              123

#{1} means the second argument in format() which is 8 in this example

'{0:{1}b}'.format(123,8)=  1111011

#{1} means the second argument in format() which is 16 in this example

'{0:{1}b}'.format(123.16)=          1111011

Format with digit and base specification ======

#{1} means the second argument in format() which is 8 in this example

#{2} means the third argument in format() which is 'd' in this example

'{0:{1}{2}}'.format(123,8)=      123

#{1} means the second argument in format() which is 16 in this example

#{2} means the third argument in format() which is 'd' in this example

'{0:{1}{2}}'.format(123.16)=              123

#{1} means the second argument in format() which is 16 in this example

#{2} means the third argument in format() which is 'd' in this example

'{0:0{1}{2}}'.format(123.16)= 0000000000000123

#{1} means the second argument in format() which is 8 in this example

#{2} means the third argument in format() which is 'b' in this example

'{0:{1}{2}}'.format(123,8)=  1111011

#{1} means the second argument in format() which is 16 in this example

#{2} means the third argument in format() which is 'b' in this example

'{0:{1}{2}}'.format(123.16)=          1111011

#{1} means the second argument in format() which is 16 in this example

#{2} means the third argument in format() which is 'b' in this example

'{0:0{1}{2}}'.format(123.16)= 0000000001111011