在 Python 中如何將字符串轉(zhuǎn)換為整數(shù)
作者:Python大本營
類似于內(nèi)置的 str() 方法,Python 語言中有一個(gè)很好用的 int() 方法,可以將字符串對象作為參數(shù),并返回一個(gè)整數(shù)。
類似于內(nèi)置的 str() 方法,Python 語言中有一個(gè)很好用的 int() 方法,可以將字符串對象作為參數(shù),并返回一個(gè)整數(shù)。
用法示例:
- # Here age is a string object
- age = "18"
- print(age)
- # Converting a string to an integer
- int_age = int(age)
- print(int_age)
輸出:
- 18
- 18
盡管輸出結(jié)果看起來相似,但是,請注意第一行是字符串對象,而后一行是整數(shù)對象。在下一個(gè)示例中將進(jìn)一步說明這一點(diǎn):
- age = "18"
- print(age + 2)
輸出:
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: cannot concatenate 'str' and 'int' objects
通過這個(gè)報(bào)錯(cuò),你應(yīng)該明白,你需要先將 age 對象轉(zhuǎn)換為整數(shù),然后再向其中添加內(nèi)容。
- age = "18"
- age_int = int(age)
- print(age_int + 2)
輸出:
- 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ù)。
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ValueError: invalid literal for int() with base 10: '7.9'
- 單詞作為參數(shù)時(shí),將返回相同的錯(cuò)誤。例如,print(int("one")) 將返回:
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ValueError: invalid literal for int() with base 10: 'one'
責(zé)任編輯:華軒
來源:
今日頭條