如何在Python中將字串轉換為數字?

王林
發布: 2023-08-26 19:37:03
轉載
3658 人瀏覽過

如何在Python中將字串轉換為數字?

要將字串轉換為數字,有多種方法。讓我們一一看看。

使用 int() 將字串轉換為數字

範例

在此範例中,我們將使用 int() 方法將字串轉換為數字 -

# String to be converted
myStr = "200"

# Display the string and it's type
print("String = ",myStr)
print("Type= ", type(myStr))

# Convert the string to integer using int() and display the type
myInt = int(myStr)
print("\nInteger = ", myInt)
print("Type = ", type(myInt))
登入後複製

輸出

String =  200
Type=  <class 'str'>

Integer =  200
Type =  <class 'int'>
登入後複製

使用 float() 將字串轉換為數字

範例

在此範例中,我們將使用 float() 方法將字串轉換為浮點數,然後使用 int() 方法將浮點數轉換為整數 -

# String to be converted
myStr = "500"

# Display the string and it's type
print("String = ",myStr)
print("Type= ", type(myStr))

# Convert the string to float
myFloat = float(myStr)
print("\nFloat = ", myFloat)
print("Type = ", type(myFloat))

# Convert the float to int
myInt = int(myFloat)
print("\nInteger = ", myInt)
print("Type = ", type(myInt))
登入後複製

輸出

String =  500
Type=  <class 'str'>

Float =  500.0
Type =  <class 'float'>

Integer =  500
Type =  <class 'int'>
登入後複製

將字串轉換為數字base10和base8

範例

在此範例中,我們將使用帶有基本參數的 int() 將字串轉換為數字。

# String to be converted
myStr = "500"

# Display the string and it's type
print("String = ",myStr)
print("Type= ", type(myStr))

# Convert the string to int
myInt1 = int(myStr)
print("\nInteger (base10) = ", myInt1)
print("Type = ", type(myInt1))

# Convert the string to int
myInt2 = int(myStr, base=8)
print("\nInteger (base8) = ", myInt2)
print("Type = ", type(myInt2))
登入後複製

輸出

String =  500
Type=  <class 'str'>
Integer (base10) =  500
Type =  <class 'int'>

Integer (base8) =  320
Type =  <class 'int'>
登入後複製

以上是如何在Python中將字串轉換為數字?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!