The complete guide to converting data types to Python: built-in functions for working with types
Data type casting is one of the most popular applications in Python, which allows you to change the data type depending on the type of user. meaning. Python is a programmable set of embedded modules for using so-called transformations, which makes working with various types of data flexible and enjoyable.
In this detailed guide, we will look at all the basic type conversion functions, their parameters, usage features, and practical application examples.
1. int(x, base=10) is the transformation of all this
Function type int() converts an object to an integer and is one of the most frequently used conversion functions.
Parameters:
x- object for conversion (string, word with a perfect dot, strong language)base- familiarization with the number system (10 in total, maybe from 2 to 36)
Use cases:
# Converting a string to an
int value('10') # Returns 10
int('123') # Returns 123
# Converting a floating point number (the fractional part is discarded)
int(10.5) # Gets 10
int(3.9) # Gets 3
int(-2.7) # Gets -2
# Working with different control systems
int('1010', 2) # Returns 10 (dual system)
int('FF', 16) # Returns 255 (electronic system)
int('77', 8) # Returns 63 (general system)
# Conversion of logical
int values(True) # Returns 1
int(False) # Returns 0
Information:
# ValueError has the incorrect form
int('abc') # Cause ValueError
int('10.5') # Cause ValueError (semicolon string)
2. float(x) - Change in the floating-point result
The float() function converts an object to just a floating point.
Parameters:
xis an object for conversion (strict, simple, tough nut to crack)
Use cases:
# String conversion
float('3.14') # Returns 3.14
floating point number('10') # Reaches 10.0
floating point number('-5.5') # Reaches -5.5
# Integer conversion
floating point number(10) # returns 10.0
floating point number(-3) # returns -3.0
# Special
values floating point value('inf') # Returns inf (automatically)
float('-inf') # Returns -inf (external security)
float('nan') # Returns nan(none)
# Boolean conversion
floating point value(True) # Changes to 1.0
floating point value(False) # Changes to 0.0
3. str(object, encoding='utf-8', errors='strict') - String conversion
Link str() is a text in a string representation.
Parameters:
objectis the object to convertencoding- encoding for byte texts (including 'utf-8')- - please help me find the code
Use cases:
# Text conversion
street(10) # Returns '10'
street(3.14) # Returns '3.14'
str(-5) # Returns '-5'
# Changing the logical value
of str(True) # Returns 'True'
str(False) # Returns 'False'
# Converting
Street Collections([1, 2, 3]) # Returns '[1, 2, 3]'
str({'a':1}) # Returns "{'a': 1}"
# Working with
str byte objects(b' hello', 'utf-8') # Returns 'hello'
4. bool(x) - Conversion to a boolean value
The bool() function converts an object to a boolean value (True or False).
The value that you consider to be False:
NoFalse- Basic values:
0,0.0,0j - Possible combinations:
",(),[],{},install() - Leave comments
Usage examples:
# Numbers
bool(0) # Returns False
bool(1) # Returns the True value
bool(-1) # Returns the True value
bool(0.0) # Returns False
bool(3.14) # Returns the True value
# Lines
bool(") # Returns an error
bool('hello') # Returns the True value
bool(' ') # Returns True (a space is a character)
# Collections
bool([]) # Returns False value
bool([1, 2]) # Returns the True value
bool({}) # Returns False
bool({'a': 1}) # Returns the True value
# Special values
bool(None) # returns the value False
5. list(repeatable) - Conversion to a list
Link list() creates a new experience from another world.
Parameters:
repeatableis an iterable object (string, tuple, set, section, etc.)
Use cases:
# String conversion
list('hello') # Returns ['h', 'e', 'l', 'l', 'o']
list('123') # Returns ['1', '2', '3']
#
List tuple transformation((1, 2, 3)) # Reproduces [1, 2, 3]
# Transformation of a set
the list({1, 2, 3}) # Returns [1, 2, 3] (you don't have to register yet)
# Range conversion
list(range(5)) # Returns [0, 1, 2, 3, 4]
list(range(2, 8, 2)) # Returns [2, 4, 6]
# Dictionary conversion (keys only)
list({'a':1, 'b':2}) # Returns ['a', 'b']
# Creating an empty list
list() # returns []
6. tuple(repeatable) - Conversion to a tuple
The tuple() function creates a new tuple from an iterable object.
Use cases:
# String conversion
tuple('hello') # Returns ('h', 'e', 'l', 'l', 'o')
# List Conversion
the tuple([1, 2, 3]) # Returns (1, 2, 3)
# Transformation of a set
of tuples({1, 2, 3}) # Returns (1, 2, 3) (may not be noticed yet)
# Converting a range
to a tuple(range(3)) # returns (0, 1, 2)
# Creating an empty tuple
tuple() # returns ()
7. set(repeatable) - Transformation into a set
set() function creates a new set of functions from an iterable object, automatic shock duplicates.
Use cases:
# String conversion (removes duplications)
set('hello') # Return {'h', 'e', 'l', 'o'}
# List conversion (removes duplicates)
install([1, 2, 3, 3, 2]) # Reproduces {1, 2, 3}
#
Set tuple conversion((1, 2, 3)) # Reproduces {1, 2, 3}
# Removing duplicates from
the original list = [1, 2, 2, 3, 3, 3]
unique = list(set(original)) # [1, 2, 3] (the order may vary)
# Creating the entire set
of sets() # Resumes the set()
8. dict() - Word conversion
The dict() function creates a new dictionary with different sentences.
Please provide the name:
# From this example, the key value
is dict([(1, "one"), (2, "two")]) # Returns {1: "one", 2: "two"}
# Of two messages from
the dict zip code(zip(['a', 'b'], [1, 2])) # Returns {'a': 1, 'b':2}
# From named arguments
dictation(name= "John", age=30) # Returns {'name': 'John', 'age': 30}
# From another dictionary (creates a copy)
original = {'x': 1, 'y':2}
new_dict = dict(original) # Returns {'x': 1, 'y':2}
# From
the dict list of lists([['a', 1], ['b', 2]]) # Returns {'a': 1, 'b':2}
# Creating an empty
dict dictionary() # Returns {}
Additional type conversion functions
9. complex(real, imaginary=0) - Creating a complex world
complex(3, 4) # Returns (3+4j)
complex('3+4j') # Returns (3+4j)
complex(5) # returns (5+0j)
10. bytes(source, encoding, errors) - Creating byte text
bytes('hello', 'utf-8') # Returns b' hello'
bytes([65, 66, 67]) # Returns b' ABC'
byte(5) # Returns b'\x00\x00\x00\x00\x00\x00'
11. bytearray() - Creating multiple files
bytearray('hello', 'utf-8'
) # Returns bytearray('hello') to bytearray([65, 66, 67]) # Calls bytearray(b'ABC')
Practical usage examples
Example 1: Validating and converting user input
def get_integer_input(request):
if True:
try:
user_input = input(prompt)
returns the int value(user_input)
except for the ValueError error:
print ("Please enter the keyword.")
age = get_integer_input("Enter your age: ")
Example 2: Working with the difference in the number system
# Converting words to different system values
number = 255
binary = bin(number)[2:] # '111111111'
octal = oct(number)[2:] # '377'
hexadecimal = hexadecimal(number)[2:] # 'ff'
# Reverse conversion
output(int(binary, 2)) # 255
output(int(octal, 8)) # 255
output(int(hexadecimal, 16)) # 255
Example 3: Overview of duplicate data
# Removing duplicates from a query while maintaining
the duplicate deletion order(lst):
viewed = installed()
result = []
for an element in lst:
if the element is not in seen:
viewed.add a result (element)
.add(element)
returns the result
source_list = [1, 2, 2, 3, 1, 4, 3, 5]
clear_list = delete duplicates(original_list)