- Learning Python for Forensics
- Preston Miller Chapin Bryce
- 364字
- 2021-08-20 10:17:02
Data type conversions
In some situations, the initial data type might not be the desired data type and needs to be changed while preserving its content. For example, when a user inputs arguments from the command line, they are commonly captured as strings and sometimes that user input needs to be, for example, an integer. We would need to use the integer class constructor to convert that string object before processing the data. Imagine we have a simple script that returns the square of a user-supplied integer; we would need to first convert the user input to an integer prior to squaring the input. One of the most common ways to convert data types is to wrap the variable or string with the constructor method, as shown here, for each of the data types:
>>> int('123456') # The string 123456
123456 # Is now the integer 123456
>>> str(45) # The integer 45
'45' # Is now the string 45
>>> float('37.5') # The string 37.5
37.5 # Is now the float 37.5
Invalid conversions, for example, converting the letter 'a' to an integer, will raise a ValueError. This error will state that the specified value cannot be converted to the desired type. In this case, we would want to use the built-in ord() method, which converts a character to its integer equivalent based on the ASCII value. In other scenarios, we may need to use other methods to convert between data types. The following is a table of common built-in data type conversion methods we can utilize for most scenarios:

We can also interchange the type or ordered collections found in our list, set, and tuple types. Since sets have requirements for what data may be inserted, we generally do not cast anything to a set. It is more common, instead, to case a set to a list so that we can access values by position:
>>> tuple_1 = (0, 1, 2, 3, 3)
>>> tuple_1
(0, 1, 2, 3, 3)
>>> set_1 = set(tuple_1)
>>> set_1
{0, 1, 2, 3}
>>> list_1 = list(tuple_1)
>>> list_1
[0, 1, 2, 3, 3]
>>> list_2 = list(set_1)
>>> list_2
[0, 1, 2, 3]
- unidbg逆向工程:原理與實(shí)踐
- INSTANT Netcat Starter
- Mobile Forensics Cookbook
- 計(jì)算機(jī)網(wǎng)絡(luò)安全技術(shù)(第6版·慕課版)
- 零信任網(wǎng)絡(luò):在不可信網(wǎng)絡(luò)中構(gòu)建安全系統(tǒng)
- 黑客攻防與網(wǎng)絡(luò)安全從新手到高手(絕招篇)
- Building a Home Security System with BeagleBone
- 安全防御入門手冊(cè)
- Mastering Python for Networking and Security
- Mastering Linux Security and Hardening
- 交換機(jī)·路由器·防火墻(第2版)
- 云計(jì)算安全:關(guān)鍵技術(shù)、原理及應(yīng)用
- 紅藍(lán)攻防:技術(shù)與策略(原書第3版)
- Hands-On Bug Hunting for Penetration Testers
- 網(wǎng)絡(luò)安全技術(shù)及應(yīng)用實(shí)踐教程