Search
You exceeded the request by
0 characters

10. Conversion and type checking in Python

The test was not passed
0
0

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() and str().

- The bin() and hex() 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:

Example (python)
a = int('20')
type(a) # => <class 'int'>        

Using the int() function, you can convert a number written in binary format to a decimal notation:

Example (python)
a = int('110011', 2)
a # => 51        

You can convert a decimal number to binary format using the bin() function:

Example (python)
a = bin(20)
a # => 0b10100        

Similarly, you can convert to hexadecimal format using the hex() function:

Example (python)
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:

Example (python)
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:

Example (python)
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:

Example (python)
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():

Example (python)
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:

Example (python)
a = str(10)
print("Answer: " + a) # => Answer: 10       

Type checking

There may be problems when converting types, for example:

Example (python)
a = list(10) # => TypeError: 'int' object is not iterable       

Or such:

Example (python)
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:

Example (python)
'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.

Example (python)
'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:

Example (python)
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

Two seconds...
For the first time on the Codebra website?

Sorry about this pop-up, they annoy me too.

The codebra.ru educational resource is entirely dedicated to programming and computer security. All courses and lessons are on the main page. For the sake of interest, you can look at the content of courses on Active Directory Pentest, Python, HTML and CSS, JavaScript, C++ and others posted on the main page.

If you haven't found something, then use the site search, which is located on the main page at the very top.

Good luck learning!

Close the window