- Learning Python for Forensics
- Preston Miller Chapin Bryce
- 261字
- 2021-07-02 16:41:09
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, the commands are commonly captured as strings and sometimes that user input needs to be, for example, an integer. We 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 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 seen in the following example 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 might need to use other methods to convert data types. The following is a table of common built-in data type conversion methods that we can utilize for most scenarios.

- UNIX編程藝術(shù)
- Oracle從入門到精通(第3版)
- 從零構(gòu)建知識圖譜:技術(shù)、方法與案例
- Django+Vue.js商城項目實(shí)戰(zhàn)
- 零基礎(chǔ)學(xué)C++程序設(shè)計
- Learning Chef
- 云原生Spring實(shí)戰(zhàn)
- Mastering Julia
- Java程序設(shè)計與實(shí)踐教程(第2版)
- EPLAN實(shí)戰(zhàn)設(shè)計
- Android 應(yīng)用案例開發(fā)大全(第3版)
- 量化金融R語言高級教程
- Python圖形化編程(微課版)
- 好好學(xué)Java:從零基礎(chǔ)到項目實(shí)戰(zhàn)
- Internet of Things with ESP8266