0 characters
10. Conversion and type checking in Python
Summary- In the previous lesson, conditional statements
if/elif/else
in Python are considered.- The ability to convert types is a useful skill when working with a strongly typed language.
- 7 functions for type conversion are considered:
int()
,bin()
,hex()
,list()
,set()
,tuple()
andstr()
.- The
bin()
andhex()
functions return the result as a string.- Lists can only be converted to iterable objects.
- The
set()
function is used to convert a string or other iterable object into a set.- Problems may occur when converting types, such as type checking errors.
- The
isdigit()
method is used to check a string for the presence of only digits.- The
type()
function returns the type of the object passed in the parameter.
Introduction
In the previous lesson we got acquainted with the conditional instruction if/elif/else
in Python. Although we have already touched on type conversion in the lesson about data types, and you have felt the need for them in practice for a strongly typed language, let's look at them again anyway and learn how to check them to avoid ridiculous situations when converting from one type to another.
Type conversion
Consider 7 functions: int()
, bin()
, hex()
, list()
, set()
, tuple()
and `str()'.
To convert a string to a number, use the int()
function:
a = int('20')
type(a) # => <class 'int'>
Using the int()
function, you can convert a number written in binary format to a decimal notation:
a = int('110011', 2)
a # => 51
You can convert a decimal number to binary format using the bin()
function:
a = bin(20)
a # => 0b10100
Similarly, you can convert to hexadecimal format using the hex()
function:
a = hex(20)
a # => 0x14
Note that the bin()
and hex()
functions return the result as a string.
We have not yet considered the lists (they will be discussed later), but we will still consider how to convert a string to a list:
a = list('Hello')
a # => ['H', 'e', 'l', 'l', 'o']
Note that only iterable objects (strings, tuples, dictionaries, files) can be converted to the list, i.e. those objects that can return elements one at a time. It may not be completely clear right now, but it will become clearer later.
To convert a string (or other iterable object) into a set, use the set()
function:
a = set('Hello, World')
a # => {'H', 'd', 'l', 'o', ' ', 'W', 'r', ',', 'e'}
Let me remind you that a set is a changeable, unordered sequence of unique elements. The following is an example of how to get all the unique items in the list:
a = set([1, 1, 2, 2, 3, 3, 3, 3, 3, 5])
a # => {1, 2, 3, 5}
To convert an object into a tuple, there is a function tuple()
:
a = tuple([1, 2, 3, 4, 5])
a # => (1, 2, 3, 4, 5)
Let me remind you that a tuple is an immutable list.
And the last function is str()
, to convert an object to a string:
a = str(10)
print("Answer: " + a) # => Answer: 10
Type checking
There may be problems when converting types, for example:
a = list(10) # => TypeError: 'int' object is not iterable
Or such:
a = int('b') # => invalid literal for int() with base 10: 'b'
The problem seems far-fetched. But still, sometimes it becomes necessary to check what type of data we are working with. For example, you need to go through a list of strings and convert all elements containing numbers to a numeric type. There is an isdigit()
method for these purposes. The isdigit()
method returns True
if the string consists of only digits:
'a'.isdigit() # => False
'20a'.isdigit() # => False
'20'.isdigit() # => True
To check a string for the presence of only letters in its composition, use the isalpha()
method.
'a'.isalpha() # => True
'20a'.isalpha() # => False
And the last method is isalnum()
, which checks whether the string consists of numbers or letters.
Often, based on the result obtained (string, number, list, etc.), it is necessary to build the course of the program using the conditional construction that you learned about in the previous lesson:
a = 'Hello'
a = list(a)
if (type(a) == str):
print('String')
elif (type(a) == list):
print('List)
This is helped by the type()
function, which returns the type of the object passed in the parameter.
In this lesson, we once again repeated the conversion of some types into others and learned how to determine the type of a variable for subsequent correct processing.
In the next lesson we will learn how to call Python methods in a chain.
Test task
Subscribe to our Telegram channel!
News, useful material,
programming and InfoSec