在五分钟内学习使用Python进行类型转换

by PALAKOLLU SRI MANIKANTA

通过PALAKOLLU SRI MANIKANTA

在五分钟内学习使用Python进行类型转换 (Learn typecasting in Python in five minutes)

以非常详尽的方式介绍了Python中的类型转换和类型转换的速成课程 (A crash course on Typecasting and Type conversion in Python in a very non-verbose manner)

铸件 (TypeCasting)

The process of converting one data type to another data type is called Typecasting or Type Coercion or Type Conversion.

将一种数据类型转换为另一种数据类型的过程称为TypecastingType CoercionType Conversion

The topics that I’ll be focusing on in this article are:

我将在本文中重点讨论的主题是:

  1. Implicit Type Conversion

    隐式类型转换
  2. Explicit Type Conversion

    显式类型转换
  3. Advantages

    优点
  4. Disadvantages

    缺点

隐式类型转换 (Implicit Type Conversion)

When the type conversion is performed automatically by the interpreter without the programmer’s intervention, that type of conversion is referred to as implicit type conversion.

当解释器自动执行类型转换而无需程序员干预时,该类型的转换称为隐式类型转换

示例程序: (Example Program:)
myInt = 143     # Integer value.myFloat = 1.43  # Float value.
myResult = myInt + myFloat   # Sum result
print("datatype of myInt:",type(myInt))print("datatype of myFloat:",type(myFloat))
print("Value of myResult:",myResult)print("datatype of myResult:",type(myResult))
输出: (Output:)

The output for the above program will be:

上面程序的输出将是:

datatype of myInt: <class 'int'>datatype of myFloat: <class 'float'>Value of myResult: 144.43datatype of myResult: <class 'float'>

In the above program,

在上面的程序中,

  • We add two variables myInt and myFloat, storing the value in myResult.

    我们添加两个变量myInt和myFloat,将值存储在myResult中。
  • We will look at the data type of all three objects respectively.

    我们将分别查看所有三个对象的数据类型。
  • In the output, we can see the datatype of myInt is an integer, the datatype of myFloat is a float.

    在输出中,我们可以看到myInt的数据类型是integer ,myFloat的数据类型是float

  • Also, we can see the myFloat has float data type because Python converts smaller data type to larger data type to avoid the loss of data.

    此外,我们可以看到myFloat具有float数据类型,因为Python会将较小的数据类型转换为较大的数据类型,以避免数据丢失。

This type of conversion is called Implicit Type conversion (or) UpCasting.

这种类型的转换称为隐式类型转换 (或) UpCasting

显式类型转换 (Explicit Type Conversion)

In Explicit Type Conversion, users convert the data type of an object to the required data type. We use predefined in-built functions like:

在“显式类型转换”中,用户将对象的数据类型转换为所需的数据类型。 我们使用预定义的内置函数,例如:

  1. int()

    int()
  2. float()

    浮动()
  3. complex()

    复杂()
  4. bool()

    bool()
  5. str()

    str()

The syntax for explicit type conversion is:

显式类型转换的语法为:

(required_datatype)(expression)

This type of conversion is called Explicit Type conversion (or) DownCasting.

这种类型的转换称为显式 类型转换 (或DownCasting)

整数转换 (Int Conversion)

We can use this function to convert values from other types to int.

我们可以使用此函数将其他类型的值转换为int。

For example:

例如:

>>> int(123.654)123
>>>int(False)0
>>> int("10")10
>>> int("10.5")ValueError: invalid literal for int() with base 10: '10.5'
>>> int("ten")ValueError: invalid literal for int() with base 10: 'ten'
>>> int("0B1111")ValueError: invalid literal for int() with base 10: '0B1111'
>>> int(10+3j)TypeError: can't convert complex to int
注意: (Note:)
  1. You can’t convert complex datatype to int

    您不能将复杂的数据类型转换为int
  2. If you want to convert string type to int type, the string literal must contain the value in Base-10

    如果要将字符串类型转换为int类型,则字符串文字必须包含Base-10中的值
浮点转换 (Float Conversion)

This function is used to convert any data type to a floating point number.

此函数用于将任何数据类型转换为浮点数。

For example:

例如:

>>> float(10) 10.0
>>> float(True)1.0
>>> float(False)0.0
>>> float("10")10.0
>>> float("10.5")10.5
>>> float("ten")ValueError: could not convert string to float: 'ten'
>>> float(10+5j)TypeError: can't convert complex to float
>>> float("0B1111")ValueError: could not convert string to float: '0B1111'
注意: (Note:)
  1. You can convert complex type to float type value.

    您可以将复杂类型转换为浮点类型值。
  2. If you want to convert string type to float type, the string literal must contain the value in base-10.

    如果要将字符串类型转换为浮点类型,则字符串文字必须包含以10为底的值。
复合转换 (Complex Conversion)

This function is used to convert real numbers to a complex (real, imaginary) number.

该功能 用于将实数转换为复数(实数,虚数)。

表格1:复数(x) (Form 1: complex (x))

You can use this function to convert a single value to a complex number with real part x and imaginary part 0.

您可以使用此函数将单个值转换为具有实部x和虚部0的复数。

For example:

例如:

>>> complex(10)10+0j
>>> complex(10.5)10.5+0j
>>> complex(True)1+0j
>>> complex(False)0+0j
>>> complex("10")10+0j
>>> complex("10.5")10.5+0j
>>> complex("ten")ValueError: complex() arg is a malformed string
形式2:复数(x,y) (Form 2: complex (x, y))

If you want to convert X and Y into complex number such that X will be real part and Y will be imaginary part.

如果要将X和Y转换为复数,使得X将是实部而Y将是虚部。

For example:

例如:

>>> complex(10,-2)10-2j
>>> complex(True, False)1+0j
布尔转换 (Boolean Conversion)

This function is used to convert any data type to boolean data type easily. It is the most flexible data type in Python.

此函数用于轻松地将任何数据类型转换为布尔数据类型。 它是Python中最灵活的数据类型。

For example:

例如:

>>> bool(0)False
>>> bool(1)True
>>> bool(10)True
>>> bool(0.13332)True
>>> bool(0.0)False
>>> bool(10+6j)True
>>> bool(0+15j)True
>>> bool(0+0j)False
>>> bool("Apple")True
>>> bool("")False
Note: With the help of bool function, you can convert any type of datatype into boolean and the output will be - For all values it will produce True except 0, 0+0j and for an Empty String.
注意:借助bool函数,您可以将任何类型的数据类型转换为布尔值,并且输出将为-对于所有值,除0、0 + 0j和空字符串外,它将生成True。
字符串转换 (String Conversion)

This function is used to convert any type into a string type.

此函数用于将任何类型转换为字符串类型。

For example:

例如:

>>> str(10)'10'
>>> str(10.5)'10.5'
>>> str(True)'True'
>>> str(False)'False'
>>> str(10+5j)'10+5j'
>>> str(False)'False'
示例程序: (Example Program:)
integer_number = 123  # Intstring_number = "456" # String
print("Data type of integer_number:",type(integer_number))print("Data type of num_str before Type Casting:",type(num_str))
string_number = int(string_number)print("Data type of string_number after Type Casting:",type(string_number))
number_sum = integer_number + string_number
print("Sum of integer_number and num_str:",number_sum)print("Data type of the sum:",type(number_sum))
输出: (Output:)

When we run the above program the output will be:

当我们运行上面的程序时,输出将是:

Data type of integer_number: <class 'int'>Data type of num_str before Type Casting: <class 'str'>Data type of string_number after Type Casting: <class 'int'>Sum of integer_number and num_str: 579Data type of the sum: <class 'int'>

In the above program,

在上面的程序中

  • We add string_number and integer_number variable.

    我们添加string_number和integer_number变量。
  • We converted string_number from string(higher) to integer(lower) type using int() function to perform addition.

    我们使用int()函数将string_number从string(higher)转换为integer(lower)类型以执行加法。

  • After converting string_number to an integer value Python adds these two variables.

    将string_number转换为整数值后,Python会添加这两个变量。
  • We got the number_sum value and data type to be an integer.

    我们获得了number_sum值和数据类型为整数。

类型转换的优点 (Advantages Of Typecasting)

  1. More convenient to use

    使用更方便

类型转换的缺点 (Disadvantages Of Typecasting)

  1. More complex type system

    更复杂的类型系统
  2. Source of bugs due to unexpected casts

    由于意外的强制转换导致的错误来源

I covered pretty much everything that is required to perform any type of typecasting operation in Python3.

我介绍了在Python3中执行任何类型的类型转换操作所需的几乎所有内容。

Hope this helped you learn about Python Typecasting in a quick and easy way.

希望这可以帮助您以快速简便的方式了解Python类型转换。

If you liked this article please click on the clap and leave me your valuable feedback.

如果您喜欢本文,请单击拍手,并留下宝贵的反馈给我。

翻译自: https://www.freecodecamp.org/news/learn-typecasting-in-python-in-five-minutes-90d42c439743/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值