在五分鐘內學習使用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/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391995.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391995.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391995.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Ajax post HTML 405,Web API Ajax POST向返回 405方法不允許_jquery_開發99編程知識庫

因此&#xff0c;我有一個像這樣的jquery ajax請求&#xff1a;function createLokiAccount(someurl) {var d {"Jurisdiction":17}$.ajax({type:"POST",url:"http://myserver:111/Api/V1/Customers/CreateCustomer/",data: JSON.stringify(d),c…

leetcode 480. 滑動窗口中位數(堆+滑動窗口)

中位數是有序序列最中間的那個數。如果序列的大小是偶數&#xff0c;則沒有最中間的數&#xff1b;此時中位數是最中間的兩個數的平均數。 例如&#xff1a; [2,3,4]&#xff0c;中位數是 3 [2,3]&#xff0c;中位數是 (2 3) / 2 2.5 給你一個數組 nums&#xff0c;有一個大…

1.0 Hadoop的介紹、搭建、環境

HADOOP背景介紹 1.1 Hadoop產生背景 HADOOP最早起源于Nutch。Nutch的設計目標是構建一個大型的全網搜索引擎&#xff0c;包括網頁抓取、索引、查詢等功能&#xff0c;但隨著抓取網頁數量的增加&#xff0c;遇到了嚴重的可擴展性問題——如何解決數十億網頁的存儲和索引問題。20…

如何實現多維智能監控?--AI運維的實踐探索【一】

作者丨吳樹生&#xff1a;騰訊高級工程師&#xff0c;負責SNG大數據監控平臺建設。近十年監控系統開發經驗&#xff0c;具有構建基于大數據平臺的海量高可用分布式監控系統研發經驗。 導語&#xff1a;監控數據多維化后&#xff0c;帶來新的應用場景。SNG的哈勃多維監控平臺在完…

.Net Web開發技術棧

有很多朋友有的因為興趣&#xff0c;有的因為生計而走向了.Net中&#xff0c;有很多朋友想學&#xff0c;但是又不知道怎么學&#xff0c;學什么&#xff0c;怎么系統的學&#xff0c;為此我以我微薄之力總結歸納寫了一篇.Net web開發技術棧&#xff0c;以此幫助那些想學&#…

使用Python和MetaTrader在5分鐘內開始構建您的交易策略

In one of my last posts, I showed how to create graphics using the Plotly library. To do this, we import data from MetaTrader in a ‘raw’ way without automation. Today, we will learn how to automate this process and plot a heatmap graph of the correlation…

卷積神經網絡 手勢識別_如何構建識別手語手勢的卷積神經網絡

卷積神經網絡 手勢識別by Vagdevi Kommineni通過瓦格德維科米尼(Vagdevi Kommineni) 如何構建識別手語手勢的卷積神經網絡 (How to build a convolutional neural network that recognizes sign language gestures) Sign language has been a major boon for people who are h…

spring—第一個spring程序

1.導入依賴 <dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.9.RELEASE</version></dependency>2.寫一個接口和實現 public interface dao {public void save(); }…

請對比html與css的異同,css2與css3的區別是什么?

css主要有三個版本&#xff0c;分別是css1、css2、css3。css2使用的比較多&#xff0c;因為css1的屬性比較少&#xff0c;而css3有一些老式瀏覽器并不支持&#xff0c;所以大家在開發的時候主要還是使用css2。CSS1提供有關字體、顏色、位置和文本屬性的基本信息&#xff0c;該版…

基礎 之 數組

shell中的數組 array (1 2 3) array ([1]ins1 [2]ins2 [3]ins3)array ($(命令)) # 三種定義數組&#xff0c;直接定義&#xff0c;鍵值對&#xff0c;直接用命令做數組的值。${array[*]}${array[]}${array[0]} # 輸出數組中的0位置的值&#xff0c;*和…

Linux_異常_08_本機無法訪問虛擬機web等工程

這是因為防火墻的原因&#xff0c;把響應端口開啟就行了。 # Firewall configuration written by system-config-firewall # Manual customization of this file is not recommended. *filter :INPUT ACCEPT [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A INPUT -m st…

Building a WAMP Dev Environment [3/4] - Installing and Configuring PHP

Moved to http://blog.tangcs.com/2008/10/27/wamp-installing-configuring-php/轉載于:https://www.cnblogs.com/WarrenTang/archive/2008/10/27/1320069.html

ipywidgets_未來價值和Ipywidgets

ipywidgetsHow to use Ipywidgets to visualize future value with different interest rates.如何使用Ipywidgets可視化不同利率下的未來價值。 There are some calculations that even being easy becoming better with a visualization of his terms. Moreover, the sooner…

2019 css 框架_宣布CSS 2019調查狀態

2019 css 框架by Sacha Greif由Sacha Greif 宣布#StateOfCSS 2019調查 (Announcing the #StateOfCSS 2019 Survey) 了解JavaScript狀況之后&#xff0c;幫助我們確定最新CSS趨勢 (After the State of JavaScript, help us identify the latest CSS trends) I’ve been using C…

計算機主機后面輻射大,電腦的背面輻射大嗎

眾所周知&#xff0c;電子產品的輻射都比較大&#xff0c;而電腦是非常常見的電子產品&#xff0c;它也存在著一定的輻射&#xff0c;那么電腦的背面輻射大嗎?下面就一起隨佰佰安全網小編來了解一下吧。有資料顯示&#xff0c;電腦后面的輻射比前面大&#xff0c;長期近距離在…

spring— Bean標簽scope配置和生命周期配置

scope配置 singleton 默認值&#xff0c;單例的prototype 多例的request WEB 項目中&#xff0c;Spring 創建一個 Bean的對象&#xff0c;將對象存入到 request 域中session WEB 項目中&#xff0c;Spring 創建一個 Bean 的對象&#xff0c;將對象存入session 域中global sess…

裝飾器3--裝飾器作用原理

多思考&#xff0c;多記憶&#xff01;&#xff01;&#xff01; 轉載于:https://www.cnblogs.com/momo8238/p/7217345.html

用folium模塊畫地理圖_使用Folium表示您的地理空間數據

用folium模塊畫地理圖As a part of the Data Science community, Geospatial data is one of the most crucial kinds of data to work with. The applications are as simple as ‘Where’s my food delivery order right now?’ and as complex as ‘What is the most optim…

Windows下安裝Python模塊時環境配置

“Win R”打開cmd終端&#xff0c;如果直接在里面使用pip命令的時候&#xff0c;要么出現“syntax invalid”&#xff0c;要么出現&#xff1a; pip is not recognized as an internal or external command, operable program or batch file. 此時需要將C:\Python27\Scripts添加…

播客2008

http://blog.tangcs.com/2008/12/29/year-2008/轉載于:https://www.cnblogs.com/WarrenTang/articles/1364465.html