Python 简明教程
Python - Type Casting
Python Type Casting
从编程的角度来看,类型转换是指将一种类型的对象转换为另一种类型。在这里,我们将了解 Python 编程中的类型转换。
From a programming point of view, a type casting refers to converting an object of one type into another. Here, we shall learn about type casting in Python Programming.
在 Python 中,有不同的数据类型,例如数字、序列、映射等。在某些情况下,你可能有某一类型的数据,但你想以另一种形式使用它。例如,用户输入了一个字符串,但你想将其作为数字使用。Python 的类型转换机制让你能够做到这一点。
In Python there are different data types, such as numbers, sequences, mappings etc. There may be a situation where, you have the available data of one type but you want to use it in another form. For example, the user has input a string but you want to use it as a number. Python’s type casting mechanism let you do that.
Python Implicit Casting
当任何语言编译器/解释器自动将一种类型转换为另一种类型时,称为自动或 implicit casting 。Python 是一种强类型语言。它不允许在不相关的类型之间自动进行类型转换。例如,字符串不能转换为任何数字类型。然而,可以将整数转换为浮点数。其他语言(例如 JavaScript)是一种弱类型语言,其中整数被强制转换为字符串以进行连接。
When any language compiler/interpreter automatically converts object of one type into other, it is called automatic or implicit casting. Python is a strongly typed language. It doesn’t allow automatic type conversion between unrelated data types. For example, a string cannot be converted to any number type. However, an integer can be cast into a float. Other languages such as JavaScript is a weakly typed language, where an integer is coerced into a string for concatenation.
请注意,每种数据类型的内存需求是不同的。例如,Python 中的 integer 对象占用 4 个字节的内存,而 float 对象由于其小数部分而需要 8 个字节。因此,Python 解释器不会自动将 float 转换为 int ,因为这将导致数据丢失。另一方面,可以很容易地将 int 转换为 float ,方法是将其小数部分设置为 0。
Note that memory requirement of each data type is different. For example, an integer object in Python occupies 4 bytes of memory, while a float object needs 8 bytes because of its fractional part. Hence, Python interpreter doesn’t automatically convert a float to int, because it will result in loss of data. On the other hand, int can be easily converted into float by setting its fractional part to 0.
隐式 int 至 float 转换在 int 和 float 操作数上的任何算术运算发生时进行。
Implicit int to float casting takes place when any arithmetic operation on int and float operands is done.
考虑我们有 int 和 float 变量
Consider we have an ,int and one float variable
<<< a=10 # int object
<<< b=10.5 # float object
为了执行其加法,10 - 整数对象升级为 10.0。它是一个浮点数,但相当于其早期的数字值。现在,我们可以对两个浮点数执行加法。
To perform their addition, 10 − the integer object is upgraded to 10.0. It is a float, but equivalent to its earlier numeric value. Now we can perform addition of two floats.
<<< c=a+b
<<< print (c)
20.5
在隐式类型转换中,具有较小字节大小的 Python 对象将升级为与操作中另一个对象的较大字节大小匹配。例如,布尔对象首先升级为 int,然后升级为 float,然后再与浮点数对象相加。在以下示例中,我们尝试在浮点数中添加一个布尔对象,请注意 True 等于 1,而 False 等于 0。
In implicit type casting, a Python object with lesser byte size is upgraded to match the bigger byte size of other object in the operation. For example, a Boolean object is first upgraded to int and then to float, before the addition with a floating point object. In the following example, we try to add a Boolean object in a float, pleae note that True is equal to 1, and False is equal to 0.
a=True;
b=10.5;
c=a+b;
print (c);
这将产生以下结果:
This will produce the following result:
11.5
Python Explicit Casting
虽然自动或隐式转换仅限于 int 至 float 转换,但您可以使用 Python 的内置函数 int()、float() 和 str() 来执行显式转换,例如字符串到整数。
Although automatic or implicit casting is limited to int to float conversion, you can use Python’s built-in functions int(), float() and str() to perform the explicit conversions such as string to integer.
Python int() Function
Python 的内置 int() 函数将整型字面量转换为整型对象,将浮点数转换为整型,将字符串转换为整型(如果字符串本身具有有效的整型字面量表示)。
Python’s built-in int() function converts an integer literal to an integer object, a float to integer, and a string to integer if the string itself has a valid integer literal representation.
将 int() 与 int 对象一起用作参数等同于直接声明 int 对象。
Using int() with an int object as argument is equivalent to declaring an int object directly.
<<< a = int(10)
<<< a
10
等同于 −
is same as −
<<< a = 10
<<< a
10
<<< type(a)
<class 'int>
如果 int() 函数的参数是浮点数对象或浮点数表达式,它会返回一个整型对象。例如,
If the argument to int() function is a float object or floating point expression, it returns an int object. For example −
<<< a = int(10.5) #converts a float object to int
<<< a
10
<<< a = int(2*3.14) #expression results float, is converted to int
<<< a
6
<<< type(a)
<class 'int'>
int() 函数也会返回整数 1,如果给定的参数是布尔对象。
The int() function also returns integer 1 if a Boolean object is given as argument.
<<< a=int(True)
<<< a
1
<<< type(a)
<class 'int'>
String to Integer
int() 函数从字符串对象返回整数,前提是字符串包含有效的整数表示。
The int() function returns an integer from a string object, only if it contains a valid integer representation.
<<< a = int("100")
<<< a
100
<<< type(a)
<class 'int'>
<<< a = ("10"+"01")
<<< a = int("10"+"01")
<<< a
1001
<<< type(a)
<class 'int'>
但是,如果字符串包含非整数表示形式,Python 将引发 ValueError。
However, if the string contains a non-integer representation, Python raises ValueError.
<<< a = int("10.5")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.5'
<<< a = int("Hello World")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello World'
int() 函数还会从二进制、八进制和十六进制字符串返回整数。为此,该函数需要一个基参数,它分别必须为 2、8 或 16。字符串应该具有有效的二进制/八进制/十六进制表示。
The int() function also returns integer from binary, octal and hexa-decimal string. For this, the function needs a base parameter which must be 2, 8 or 16 respectively. The string should have a valid binary/octal/Hexa-decimal representation.
Binary String to Integer
该字符串应仅由 1 和 0 组成,且基数应为 2。
The string should be made up of 1 and 0 only, and the base should be 2.
<<< a = int("110011", 2)
<<< a
51
二进制数 110011 的十进制等价数为 51。
The Decimal equivalent of binary number 110011 is 51.
Octal String to Integer
该字符串应仅包含 0 至 7 位数字,且基数应为 8。
The string should only contain 0 to 7 digits, and the base should be 8.
<<< a = int("20", 8)
<<< a
16
八进制数 20 的十进制等价数为 16。
The Decimal equivalent of octal 20 is 16.
Hexa-Decimal String to Integer
该字符串应仅包含十六进制符号,即 0-9 和 A、B、C、D、E 或 F。基数应为 16。
The string should contain only the Hexadecimal symbols i.e., 0-9 and A, B, C, D, E or F. Base should be 16.
<<< a = int("2A9", 16)
<<< a
681
十六进制 2A9 的十进制等价数是 681。您可以在 Windows、Ubuntu 或智能手机上的计算器应用中轻松验证这些转换。
Decimal equivalent of Hexadecimal 2A9 is 681. You can easily verify these conversions with calculator app in Windows, Ubuntu or Smartphones.
以下是将数字、浮点数和字符串转换为整数数据类型的示例:
Following is an example to convert number, float and string into integer data type:
a = int(1) # a will be 1
b = int(2.2) # b will be 2
c = int("3") # c will be 3
print (a)
print (b)
print (c)
这产生了以下结果 -
This produce the following result −
1
2
3
Python float() Function
float() 是 Python 中的内置函数。如果参数是浮点文字、整数或具有有效浮点表示的字符串,它将返回一个浮点对象。
The float() is a built-in function in Python. It returns a float object if the argument is a float literal, integer or a string with valid floating point representation.
将 float() 与 float 对象作为参数一起使用相当于直接声明一个 float 对象
Using float() with an float object as argument is equivalent to declaring a float object directly
<<< a = float(9.99)
<<< a
9.99
<<< type(a)
<class 'float'>
等同于 −
is same as −
<<< a = 9.99
<<< a
9.99
<<< type(a)
<class 'float'>
如果 float() 函数的参数是整数,则返回值是小数部分设置为 0 的浮点数。
If the argument to float() function is an integer, the returned value is a floating point with fractional part set to 0.
<<< a = float(100)
<<< a
100.0
<<< type(a)
<class 'float'>
float() 函数从字符串返回浮点对象,如果字符串包含有效的浮点数,否则会引发 ValueError。
The float() function returns float object from a string, if the string contains a valid floating point number, otherwise ValueError is raised.
<<< a = float("9.99")
<<< a
9.99
<<< type(a)
<class 'float'>
<<< a = float("1,234.50")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '1,234.50'
这里导致 ValueError 的原因是字符串中存在逗号。
The reason of ValueError here is the presence of comma in the string.
为了将字符串转换为浮点数,浮点数的科学计数法也会被视为有效计数法。
For the purpose of string to float conversion, the sceientific notation of floating point is also considered valid.
<<< a = float("1.00E4")
<<< a
10000.0
<<< type(a)
<class 'float'>
<<< a = float("1.00E-4")
<<< a
0.0001
<<< type(a)
<class 'float'>
以下是将数字、浮点数和字符串转换为浮点数据类型的示例:
Following is an example to convert number, float and string into float data type:
a = float(1) # a will be 1.0
b = float(2.2) # b will be 2.2
c = float("3.3") # c will be 3.3
print (a)
print (b)
print (c)
这产生了以下结果 -
This produce the following result −
1.0
2.2
3.3
Python str() Function
我们看到了 Python 如何从对应的字符串表示中获取整数或浮点数。 str() 函数的工作原理相反。它用引号 (') 包围整数或浮点对象以返回一个 str 对象。 str() 函数返回任何 Python 对象的字符串表示。在本节中,我们将看到 Python 中 str() 函数的不同示例。
We saw how a Python obtains integer or float number from corresponding string representation. The str() function works the opposite. It surrounds an integer or a float object with quotes (') to return a str object. The str() function returns the string representation of any Python object. In this section, we shall see different examples of str() function in Python.
str() 函数有三个参数。第一个必需参数(或自变量)是我们要获取其字符串表示的对象。另两个运算符,编码和错误,是可选的。
The str() function has three parameters. First required parameter (or argument) is the object whose string representation we want. Other two operators, encoding and errors, are optional.
我们将在 Python 控制台中执行 str() 函数,以轻松验证返回的对象是一个字符串,并有引号 (')。
We shall execute str() function in Python console to easily verify that the returned object is a string, with the enclosing quotation marks (').
Integer to string
您可以按以下方式将任何整数转换为字符串:
You can convert any integer number into a string as follows:
<<< a = str(10)
<<< a
'10'
<<< type(a)
<class 'str'>
Float to String
str() 函数将浮点数对象转化为带小数点的标准记法,即整数部分和小数部分用小数点分隔,以及带指数的科学记法,转化为字符串对象。
str() function converts floating point objects with both the notations of floating point, standard notation with a decimal point separating integer and fractional part, and the scientific notation to string object.
<<< a=str(11.10)
<<< a
'11.1'
<<< type(a)
<class 'str'>
<<< a = str(2/5)
<<< a
'0.4'
<<< type(a)
<class 'str'>
在第二个案例中,除法式被作为自变量提供给 str() 函数。请注意,表达式最先被求值,然后结果被转化为字符串。
In the second case, a division expression is given as argument to str() function. Note that the expression is evaluated first and then result is converted to string.
以 E 或 e 以及正、负幂表示的科学记法中的浮点数可以用 str() 函数转化为字符串。
Floating points in scientific notations using E or e and with positive or negative power are converted to string with str() function.
<<< a=str(10E4)
<<< a
'100000.0'
<<< type(a)
<class 'str'>
<<< a=str(1.23e-4)
<<< a
'0.000123'
<<< type(a)
<class 'str'>
当布尔常量被作为自变量输入时,它会被单引号 (') 括起来,因此 True 变成 'True'。列表和元组对象也可以作为自变量提供给 str() 函数。结果字符串是带单引号 (') 的列表/元组。
When Boolean constant is entered as argument, it is surrounded by (') so that True becomes 'True'. List and Tuple objects can also be given argument to str() function. The resultant string is the list/tuple surrounded by (').
<<< a=str('True')
<<< a
'True'
<<< a=str([1,2,3])
<<< a
'[1, 2, 3]'
<<< a=str((1,2,3))
<<< a
'(1, 2, 3)'
<<< a=str({1:100, 2:200, 3:300})
<<< a
'{1: 100, 2: 200, 3: 300}'
以下是将数字、浮点数和字符串转换为字符串数据类型的示例:
Following is an example to convert number, float and string into string data type:
a = str(1) # a will be "1"
b = str(2.2) # b will be "2.2"
c = str("3.3") # c will be "3.3"
print (a)
print (b)
print (c)
这产生了以下结果 -
This produce the following result −
1
2.2
3.3
Conversion of Sequence Types
列表、元组和字符串是 Python 中的序列类型。它们是按顺序排列或按索引排列的项目集合。
List, Tuple and String are Python’s sequence types. They are ordered or indexed collection of items.
字符串和元组可以通过使用 list() 函数转化为列表对象。类似地, tuple() 函数将字符串或列表转化为元组。
A string and tuple can be converted into a list object by using the list() function. Similarly, the tuple() function converts a string or list to a tuple.
我们将分别采用这三种顺序类型中的一个对象并研究它们的相互转换。
We shall take an object each of these three sequence types and study their inter-conversion.
<<< a=[1,2,3,4,5] # List Object
<<< b=(1,2,3,4,5) # Tupple Object
<<< c="Hello" # String Object
### list() separates each character in the string and builds the list
<<< obj=list(c)
<<< obj
['H', 'e', 'l', 'l', 'o']
### The parentheses of tuple are replaced by square brackets
<<< obj=list(b)
<<< obj
[1, 2, 3, 4, 5]
### tuple() separates each character from string and builds a tuple of characters
<<< obj=tuple(c)
<<< obj
('H', 'e', 'l', 'l', 'o')
### square brackets of list are replaced by parentheses.
<<< obj=tuple(a)
<<< obj
(1, 2, 3, 4, 5)
### str() function puts the list and tuple inside the quote symbols.
<<< obj=str(a)
<<< obj
'[1, 2, 3, 4, 5]'
<<< obj=str(b)
<<< obj
'(1, 2, 3, 4, 5)'
因此,Python 的显式类型转换特性允许借助于其内置函数,将一种数据类型转化为另一种数据类型。
Thus Python’s explicit type casting feature allows conversion of one data type to other with the help of its built-in functions.
Data Type Conversion Functions
有几个内置函数可以执行从一种数据类型到另一种数据类型的转换。这些函数会返回一个表示转换值的新对象。
There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.
Sr.No. |
Function & Description |
1 |
Python int() functionConverts x to an integer. base specifies the base if x is a string. |
2 |
Python long() functionConverts x to a long integer. base specifies the base if x is a string. |
3 |
Python float() functionConverts x to a floating-point number. |
4 |
Python complex() functionCreates a complex number. |
5 |
Python str() functionConverts object x to a string representation. |
6 |
Python repr() functionConverts object x to an expression string. |
7 |
Python eval() functionEvaluates a string and returns an object. |
8 |
Python tuple() functionConverts s to a tuple. |
9 |
Python list() functionConverts s to a list. |
10 |
Python set() functionConverts s to a set. |
11 |
Python dict() functionCreates a dictionary. d must be a sequence of (key,value) tuples. |
12 |
Python frozenset() functionConverts s to a frozen set. |
13 |
Python chr() functionConverts an integer to a character. |
14 |
Python unichr() functionConverts an integer to a Unicode character. |
15 |
Python ord() functionConverts a single character to its integer value. |
16 |
Python hex() functionConverts an integer to a hexadecimal string. |
17 |
Python oct() functionConverts an integer to an octal string. |