Str data type
In Python, a string is a sequence of characters enclosed within a single quote or double quote. These characters could be anything like letters, numbers, or special symbols enclosed within double quotation marks. For example, "Python" is a string.
The string type in Python is represented using a str class.
To work with text or characters data in Python, we use strings. Once a string is created, we can do many operations on it. Such as searching inside it, creating a substring from it, and spliting it.
Example:
str = "Python"
print(type(str)) # <class 'str'>
# display string
print(str) # 'Python'
# accessing 2nd character of a string
print(str[1]) # y
Note: The string is immutable, i.e. it can not be changed once defined. You need to create a copy of it if you want to modify it. This non-changeable behavior is called immutability.
Example:
str = 'python'
# Now let's try to change 2nd character of a string
str[0] = 'P'
# Gives TypeError: 'str' object does not support item assignment
Int data type
Python uses the int data type to represent whole integer values. For example, we can use the int data type to store the roll number of a student. The integer type in Python is represented using a int class.
You can store positive and negative interger numbers of any length such as 1, -10, 31431.
We can create an integer variable using the two ways.
- Directly assigning an integer value to a variable
- Using a int() class.
Example:
# store int value
int_number = 10
# display int_number
print("int_number is:", int_number) # output 10
# display int_number type
print(type(int_number) # output class 'int'
# store integer using int() class
id = int(25)
print(id) # 25
print(type(id)) # class 'int'
You can also store integer values other than base 10 such as:
- Binary(base 2)
- Octal (base 3)
- Hexadecimal numbers (base 16)
# decimal int 16 with base 8
# prefix with zero + letter b
octal_num = 0o20
print(octal_num) # 16
print(type(octal_num)) # class 'int'
# decimal int 16 with base 16
# prefix with zero + letter x
hexadecimal_num = 0x10 # decimal equivalent of 21
print(hexadecimal_num) # 16
print(type(hexadecimal_num)) # class 'int'
# decimal int 16 with base 2
# prefix with zero + letter b
binary_num = 0b10000 # decimal equivalent of 6
print(binary_num) # 16
print(type(binary_num)) # class 'int'