自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

在 Python 中如何將字符串轉(zhuǎn)換為整數(shù)

開發(fā) 后端
類似于內(nèi)置的 str() 方法,Python 語言中有一個(gè)很好用的 int() 方法,可以將字符串對象作為參數(shù),并返回一個(gè)整數(shù)。

 類似于內(nèi)置的 str() 方法,Python 語言中有一個(gè)很好用的 int() 方法,可以將字符串對象作為參數(shù),并返回一個(gè)整數(shù)。

[[442867]]

用法示例:

 

  1. # Here age is a string object 
  2. age = "18" 
  3. print(age) 
  4.  
  5. # Converting a string to an integer 
  6. int_age = int(age) 
  7. print(int_age) 

 

輸出:

 

  1. 18 
  2. 18 

 

盡管輸出結(jié)果看起來相似,但是,請注意第一行是字符串對象,而后一行是整數(shù)對象。在下一個(gè)示例中將進(jìn)一步說明這一點(diǎn):

 

  1. age = "18" 
  2. print(age + 2) 

 

輸出:

 

  1. Traceback (most recent call last): 
  2.   File "<stdin>", line 1, in <module> 
  3. TypeError: cannot concatenate 'str' and 'int' objects 

 

通過這個(gè)報(bào)錯(cuò),你應(yīng)該明白,你需要先將 age 對象轉(zhuǎn)換為整數(shù),然后再向其中添加內(nèi)容。

 

  1. age = "18" 
  2. age_int = int(age) 
  3. print(age_int + 2) 

 

輸出:

 

  1. 20 

但是,請記住以下特殊情況:

  • 浮點(diǎn)數(shù)(帶小數(shù)部分的整數(shù))作為參數(shù),將返回該浮點(diǎn)數(shù)四舍五入后最接近的整數(shù)。例如:print(int(7.9)) 的打印結(jié)果是 7。另一方面,print(int("7.9")) 將報(bào)錯(cuò),因?yàn)椴荒軐⒆鳛樽址畬ο蟮母↑c(diǎn)數(shù)轉(zhuǎn)換為整數(shù)。

 

  1. Traceback (most recent call last): 
  2.   File "<stdin>", line 1, in <module> 
  3. ValueError: invalid literal for int() with base 10: '7.9' 

 

  • 單詞作為參數(shù)時(shí),將返回相同的錯(cuò)誤。例如,print(int("one")) 將返回:

 

  1. Traceback (most recent call last): 
  2.   File "<stdin>", line 1, in <module> 
  3. ValueError: invalid literal for int() with base 10: 'one' 

 

責(zé)任編輯:華軒 來源: 今日頭條
相關(guān)推薦

2024-02-19 15:38:08

JsonPython字符串

2009-06-05 11:16:58

字符串動(dòng)態(tài)轉(zhuǎn)換

2024-01-04 09:17:03

前端開發(fā)CSV 格式JSON 字符串

2009-11-25 16:55:45

PHP函數(shù)explod

2016-12-30 13:16:51

字符串算法代碼

2009-07-15 16:56:59

Jython類型Java類型

2021-08-26 09:46:22

JavaScript字符串URL

2024-03-12 07:35:39

Python字符串列表

2021-11-29 00:17:41

JS符串轉(zhuǎn)換

2020-12-17 08:08:15

CentOS

2017-05-25 15:14:36

2021-11-29 08:49:37

字符串轉(zhuǎn)換整數(shù)

2009-07-31 14:09:41

c#時(shí)間格式轉(zhuǎn)換

2022-09-22 11:40:11

JavaScript數(shù)組開發(fā)

2009-12-01 14:00:37

PHP字符串轉(zhuǎn)換為數(shù)值

2023-10-16 09:26:48

CSS類型轉(zhuǎn)換

2024-05-30 08:40:41

大型語言模型LLM人工智能

2010-11-26 14:09:32

MySQL內(nèi)置函數(shù)

2010-03-31 19:15:25

Oracle函數(shù)

2011-04-08 10:16:13

文本文件ACCESS數(shù)據(jù)庫
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號