Monday 27 May 2019

bytes data type

Bytes data type:

In Python, we have several ways to store the sequences:
list, tuple,dictionary, strings.

In the same way we have other way to store the sequence is 'Bytes'..elements

Definition:

Bytes data type is a collection of byte numbers just like an array.
A byte number is any positive integer from 0 to 255 (inclusive)
A byte can store in the range from 0 to 255 and it can not store even negative numbers
Once we create the bytes data type it is not possible to modify the values

Syntax:

1. Create one list (2.) type caste into bytes

Variable=[number1,no2,no3,…]

Example:

>>> a=[10,20,30,40]#creating list
>>> type(a)
<class 'list'>
>>> a=bytes(a)#type casting into bytes data type
>>> type(a)
<class 'bytes'>
>>> for i in a:print(i) #processing each bytes #element where i varies from index 0 to size-1
10
20
30
40

In general we can use bytes and bytearray data types to represent binary information. 
Example: images, video files,…etc

2nd way to create bytes data type elements:

Syntax:
Variable=bytes([no1,n02,….etc])

Example:
>>> a=bytes([10,20,30,40])#direct way to create bytes data elements

It is not possible to modify:
>>> a[0]=15 #Error

Negative values are not allowed:
a=bytes([10,-20,30]) #Error

Bytes data type is a homogeneous collection of nos:
a=bytes([10,'sita',True,2+3j]) #Error

Bytes elements can be 0 to 255 only
>>> a=bytes([10,0,10,256]) #Error
>>> a=bytes([10,0,10,255]) #ok

Compare between Strings and Bytes

a='aws course' #string data type

c=b'aws course' #byte data type

print(type(a))

print(type(c))


Example:

a='Python'

c=b'Python'

print(type(c))

print(type(a))

print(a)

print(c)

d=a.encode('ASCII')

if(d==c):

    print("it is same")

else:

    print("it is not same")



Difference between String and byte:

 

Byte

String

It is stored in the form of bytes

It is stored in the form of characters

Directly system readable

System is not readable directly. Encoding should be done to understand the system

 


Next topic : bytearray
Previous topic: Mixed dictionary data type
dictionary data type

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...