Nếu bạn quan tâm đến hiệu suất [và tôi không đề xuất bạn nên], cách tiếp cận dựa trên thử là người chiến thắng rõ ràng [so với phương pháp dựa trên phân vùng của bạn hoặc phương pháp RegEXP], miễn là bạn không mong đợi nhiều Các chuỗi không hợp lệ, trong trường hợp đó nó có khả năng chậm hơn [có lẽ là do chi phí xử lý ngoại lệ].
Một lần nữa, tôi không đề nghị bạn quan tâm đến hiệu suất, chỉ cung cấp cho bạn dữ liệu trong trường hợp bạn đang thực hiện việc này 10 tỷ lần một giây hoặc một cái gì đó. Ngoài ra, mã dựa trên phân vùng không xử lý ít nhất một chuỗi hợp lệ.
$ ./floatstr.py F.. partition sad: 3.1102449894 partition happy: 2.09208488464 .. re sad: 7.76906108856 re happy: 7.09421992302 .. try sad: 12.1525540352 try happy: 1.44165301323 . ====================================================================== FAIL: test_partition [__main__.ConvertTests] ---------------------------------------------------------------------- Traceback [most recent call last]: File "./floatstr.py", line 48, in test_partition self.failUnless[is_float_partition["20e2"]] AssertionError ---------------------------------------------------------------------- Ran 8 tests in 33.670s FAILED [failures=1]
Đây là mã [Python 2.6, RegEXP lấy từ câu trả lời của John Gietzen]:
def is_float_try[str]:
try:
float[str]
return True
except ValueError:
return False
import re
_float_regexp = re.compile[r"^[-+]?[?:\b[0-9]+[?:\.[0-9]*]?|\.[0-9]+\b][?:[eE][-+]?[0-9]+\b]?$"]
def is_float_re[str]:
return re.match[_float_regexp, str]
def is_float_partition[element]:
partition=element.partition['.']
if [partition[0].isdigit[] and partition[1]=='.' and partition[2].isdigit[]] or [partition[0]=='' and partition[1]=='.' and pa\
rtition[2].isdigit[]] or [partition[0].isdigit[] and partition[1]=='.' and partition[2]=='']:
return True
if __name__ == '__main__':
import unittest
import timeit
class ConvertTests[unittest.TestCase]:
def test_re[self]:
self.failUnless[is_float_re["20e2"]]
def test_try[self]:
self.failUnless[is_float_try["20e2"]]
def test_re_perf[self]:
print
print 're sad:', timeit.Timer['floatstr.is_float_re["12.2x"]', "import floatstr"].timeit[]
print 're happy:', timeit.Timer['floatstr.is_float_re["12.2"]', "import floatstr"].timeit[]
def test_try_perf[self]:
print
print 'try sad:', timeit.Timer['floatstr.is_float_try["12.2x"]', "import floatstr"].timeit[]
print 'try happy:', timeit.Timer['floatstr.is_float_try["12.2"]', "import floatstr"].timeit[]
def test_partition_perf[self]:
print
print 'partition sad:', timeit.Timer['floatstr.is_float_partition["12.2x"]', "import floatstr"].timeit[]
print 'partition happy:', timeit.Timer['floatstr.is_float_partition["12.2"]', "import floatstr"].timeit[]
def test_partition[self]:
self.failUnless[is_float_partition["20e2"]]
def test_partition2[self]:
self.failUnless[is_float_partition[".2"]]
def test_partition3[self]:
self.failIf[is_float_partition["1234x.2"]]
unittest.main[]
Trong ví dụ này,
3 đủ thông minh để giải thích theo nghĩa đen nhị phân và chuyển đổi nó thành một chuỗi thập phân. This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Convert a Python String to int>>> int["0x12F"]
Traceback [most recent call last]:
File "", line 1, in
ValueError: invalid literal for int[] with base 10: '0x12F'
Nếu bạn muốn một chuỗi biểu diễn một số nguyên trong một hệ thống số khác, thì bạn sẽ sử dụng chuỗi được định dạng, chẳng hạn như chuỗi F [trong Python 3.6+] và tùy chọn chỉ định cơ sở:
def is_float_try[str]:
try:
float[str]
return True
except ValueError:
return False
import re
_float_regexp = re.compile[r"^[-+]?[?:\b[0-9]+[?:\.[0-9]*]?|\.[0-9]+\b][?:[eE][-+]?[0-9]+\b]?$"]
def is_float_re[str]:
return re.match[_float_regexp, str]
def is_float_partition[element]:
partition=element.partition['.']
if [partition[0].isdigit[] and partition[1]=='.' and partition[2].isdigit[]] or [partition[0]=='' and partition[1]=='.' and pa\
rtition[2].isdigit[]] or [partition[0].isdigit[] and partition[1]=='.' and partition[2]=='']:
return True
if __name__ == '__main__':
import unittest
import timeit
class ConvertTests[unittest.TestCase]:
def test_re[self]:
self.failUnless[is_float_re["20e2"]]
def test_try[self]:
self.failUnless[is_float_try["20e2"]]
def test_re_perf[self]:
print
print 're sad:', timeit.Timer['floatstr.is_float_re["12.2x"]', "import floatstr"].timeit[]
print 're happy:', timeit.Timer['floatstr.is_float_re["12.2"]', "import floatstr"].timeit[]
def test_try_perf[self]:
print
print 'try sad:', timeit.Timer['floatstr.is_float_try["12.2x"]', "import floatstr"].timeit[]
print 'try happy:', timeit.Timer['floatstr.is_float_try["12.2"]', "import floatstr"].timeit[]
def test_partition_perf[self]:
print
print 'partition sad:', timeit.Timer['floatstr.is_float_partition["12.2x"]', "import floatstr"].timeit[]
print 'partition happy:', timeit.Timer['floatstr.is_float_partition["12.2"]', "import floatstr"].timeit[]
def test_partition[self]:
self.failUnless[is_float_partition["20e2"]]
def test_partition2[self]:
self.failUnless[is_float_partition[".2"]]
def test_partition3[self]:
self.failIf[is_float_partition["1234x.2"]]
unittest.main[]
0 là một cách linh hoạt để thể hiện số nguyên trong nhiều hệ thống số khác nhau.- Sự kết luận
- Trong Python, bạn có thể chuyển đổi Python
int
thành một chuỗi bằng cách sử dụng
3:>>> int["0x12F"] Traceback [most recent call last]: File "", line 1, in ValueError: invalid literal for int[] with base 10: '0x12F'
- Theo mặc định,
3 hoạt động như>>> int["0x12F"] Traceback [most recent call last]: File "", line 1, in ValueError: invalid literal for int[] with base 10: '0x12F'
3 ở chỗ nó dẫn đến một đại diện thập phân:>>> int["10"] 10 >>> type[int["10"]]
>>> str[0b11010010]
'210'
Trong ví dụ này, >>> int["0x12F"]
Traceback [most recent call last]:
File "", line 1, in
ValueError: invalid literal for int[] with base 10: '0x12F'
3 đủ thông minh để giải thích theo nghĩa đen nhị phân và chuyển đổi nó thành một chuỗi thập phân.
>>> int["0x12F"]
Traceback [most recent call last]:
File "", line 1, in
ValueError: invalid literal for int[] with base 10: '0x12F'
Nếu bạn muốn một chuỗi biểu diễn một số nguyên trong một hệ thống số khác, thì bạn sẽ sử dụng chuỗi được định dạng, chẳng hạn như chuỗi F [trong Python 3.6+] và tùy chọn chỉ định cơ sở:
0def is_float_try[str]: try: float[str] return True except ValueError: return False import re _float_regexp = re.compile[r"^[-+]?[?:\b[0-9]+[?:\.[0-9]*]?|\.[0-9]+\b][?:[eE][-+]?[0-9]+\b]?$"] def is_float_re[str]: return re.match[_float_regexp, str] def is_float_partition[element]: partition=element.partition['.'] if [partition[0].isdigit[] and partition[1]=='.' and partition[2].isdigit[]] or [partition[0]=='' and partition[1]=='.' and pa\ rtition[2].isdigit[]] or [partition[0].isdigit[] and partition[1]=='.' and partition[2]=='']: return True if __name__ == '__main__': import unittest import timeit class ConvertTests[unittest.TestCase]: def test_re[self]: self.failUnless[is_float_re["20e2"]] def test_try[self]: self.failUnless[is_float_try["20e2"]] def test_re_perf[self]: print print 're sad:', timeit.Timer['floatstr.is_float_re["12.2x"]', "import floatstr"].timeit[] print 're happy:', timeit.Timer['floatstr.is_float_re["12.2"]', "import floatstr"].timeit[] def test_try_perf[self]: print print 'try sad:', timeit.Timer['floatstr.is_float_try["12.2x"]', "import floatstr"].timeit[] print 'try happy:', timeit.Timer['floatstr.is_float_try["12.2"]', "import floatstr"].timeit[] def test_partition_perf[self]: print print 'partition sad:', timeit.Timer['floatstr.is_float_partition["12.2x"]', "import floatstr"].timeit[] print 'partition happy:', timeit.Timer['floatstr.is_float_partition["12.2"]', "import floatstr"].timeit[] def test_partition[self]: self.failUnless[is_float_partition["20e2"]] def test_partition2[self]: self.failUnless[is_float_partition[".2"]] def test_partition3[self]: self.failIf[is_float_partition["1234x.2"]] unittest.main[]
int
def is_float_try[str]:
try:
float[str]
return True
except ValueError:
return False
import re
_float_regexp = re.compile[r"^[-+]?[?:\b[0-9]+[?:\.[0-9]*]?|\.[0-9]+\b][?:[eE][-+]?[0-9]+\b]?$"]
def is_float_re[str]:
return re.match[_float_regexp, str]
def is_float_partition[element]:
partition=element.partition['.']
if [partition[0].isdigit[] and partition[1]=='.' and partition[2].isdigit[]] or [partition[0]=='' and partition[1]=='.' and pa\
rtition[2].isdigit[]] or [partition[0].isdigit[] and partition[1]=='.' and partition[2]=='']:
return True
if __name__ == '__main__':
import unittest
import timeit
class ConvertTests[unittest.TestCase]:
def test_re[self]:
self.failUnless[is_float_re["20e2"]]
def test_try[self]:
self.failUnless[is_float_try["20e2"]]
def test_re_perf[self]:
print
print 're sad:', timeit.Timer['floatstr.is_float_re["12.2x"]', "import floatstr"].timeit[]
print 're happy:', timeit.Timer['floatstr.is_float_re["12.2"]', "import floatstr"].timeit[]
def test_try_perf[self]:
print
print 'try sad:', timeit.Timer['floatstr.is_float_try["12.2x"]', "import floatstr"].timeit[]
print 'try happy:', timeit.Timer['floatstr.is_float_try["12.2"]', "import floatstr"].timeit[]
def test_partition_perf[self]:
print
print 'partition sad:', timeit.Timer['floatstr.is_float_partition["12.2x"]', "import floatstr"].timeit[]
print 'partition happy:', timeit.Timer['floatstr.is_float_partition["12.2"]', "import floatstr"].timeit[]
def test_partition[self]:
self.failUnless[is_float_partition["20e2"]]
def test_partition2[self]:
self.failUnless[is_float_partition[".2"]]
def test_partition3[self]:
self.failIf[is_float_partition["1234x.2"]]
unittest.main[]
0 là một cách linh hoạt để thể hiện số nguyên trong nhiều hệ thống số khác nhau.Sự kết luận
Điều quan trọng là phải xem xét những gì bạn đặc biệt có nghĩa là
>>> binary = 0b1010
>>> hexadecimal = "0xa"
0 và def is_float_try[str]:
try:
float[str]
return True
except ValueError:
return False
import re
_float_regexp = re.compile[r"^[-+]?[?:\b[0-9]+[?:\.[0-9]*]?|\.[0-9]+\b][?:[eE][-+]?[0-9]+\b]?$"]
def is_float_re[str]:
return re.match[_float_regexp, str]
def is_float_partition[element]:
partition=element.partition['.']
if [partition[0].isdigit[] and partition[1]=='.' and partition[2].isdigit[]] or [partition[0]=='' and partition[1]=='.' and pa\
rtition[2].isdigit[]] or [partition[0].isdigit[] and partition[1]=='.' and partition[2]=='']:
return True
if __name__ == '__main__':
import unittest
import timeit
class ConvertTests[unittest.TestCase]:
def test_re[self]:
self.failUnless[is_float_re["20e2"]]
def test_try[self]:
self.failUnless[is_float_try["20e2"]]
def test_re_perf[self]:
print
print 're sad:', timeit.Timer['floatstr.is_float_re["12.2x"]', "import floatstr"].timeit[]
print 're happy:', timeit.Timer['floatstr.is_float_re["12.2"]', "import floatstr"].timeit[]
def test_try_perf[self]:
print
print 'try sad:', timeit.Timer['floatstr.is_float_try["12.2x"]', "import floatstr"].timeit[]
print 'try happy:', timeit.Timer['floatstr.is_float_try["12.2"]', "import floatstr"].timeit[]
def test_partition_perf[self]:
print
print 'partition sad:', timeit.Timer['floatstr.is_float_partition["12.2x"]', "import floatstr"].timeit[]
print 'partition happy:', timeit.Timer['floatstr.is_float_partition["12.2"]', "import floatstr"].timeit[]
def test_partition[self]:
self.failUnless[is_float_partition["20e2"]]
def test_partition2[self]:
self.failUnless[is_float_partition[".2"]]
def test_partition3[self]:
self.failIf[is_float_partition["1234x.2"]]
unittest.main[]
9 trong các ví dụ trên. Là một con người đã sử dụng hệ thống số thập phân cho cả cuộc đời bạn, có thể rõ ràng là bạn có nghĩa là số một trăm mười. Tuy nhiên, có một số hệ thống số khác, chẳng hạn như nhị phân và thập lục phân, sử dụng các cơ sở khác nhau để đại diện cho một số nguyên.binary and hexadecimal, which use different bases to represent an integer.Ví dụ: bạn có thể đại diện cho số một trăm mười trong nhị phân và thập lục phân là 1101110 và 6E tương ứng.
Bạn cũng có thể đại diện cho các số nguyên của mình với các hệ thống số khác trong Python bằng cách sử dụng các loại dữ liệu ____10 và int
:
>>>
>>> binary = 0b1010
>>> hexadecimal = "0xa"
Lưu ý rằng
>>> binary = 0b1010
>>> hexadecimal = "0xa"
4 và >>> binary = 0b1010
>>> hexadecimal = "0xa"
5 sử dụng tiền tố để xác định hệ thống số. Tất cả các tiền tố số nguyên đều ở dạng >>> binary = 0b1010
>>> hexadecimal = "0xa"
6, trong đó bạn thay thế >>> binary = 0b1010
>>> hexadecimal = "0xa"
7 bằng ký tự đề cập đến hệ thống số:- B: nhị phân [cơ sở 2] binary [base 2]
- O: Octal [cơ sở 8] octal [base 8]
- D: thập phân [cơ sở 10] decimal [base 10]
- X: Hexadecimal [cơ sở 16] hexadecimal [base 16]
Bây giờ bạn có một số kiến thức nền tảng về cách thể hiện số nguyên bằng cách sử dụng ____10 và int
, bạn sẽ học cách chuyển đổi chuỗi trăn thành int
.
Chuyển đổi chuỗi Python thành int
Nếu bạn có số nguyên thập phân được biểu thị dưới dạng chuỗi và bạn muốn chuyển đổi chuỗi Python thành int
, thì bạn chỉ cần chuyển chuỗi thành
>>> int["10"]
10
>>> type[int["10"]]
3, trả về số nguyên thập phân:>>>
>>> int["10"]
10
>>> type[int["10"]]
Lưu ý rằng
>>> binary = 0b1010
>>> hexadecimal = "0xa"
4 và >>> binary = 0b1010
>>> hexadecimal = "0xa"
5 sử dụng tiền tố để xác định hệ thống số. Tất cả các tiền tố số nguyên đều ở dạng >>> binary = 0b1010
>>> hexadecimal = "0xa"
6, trong đó bạn thay thế >>> binary = 0b1010
>>> hexadecimal = "0xa"
7 bằng ký tự đề cập đến hệ thống số:>>>
>>> int["0x12F"]
Traceback [most recent call last]:
File "", line 1, in
ValueError: invalid literal for int[] with base 10: '0x12F'
Lưu ý rằng
>>> binary = 0b1010
>>> hexadecimal = "0xa"
4 và >>> binary = 0b1010
>>> hexadecimal = "0xa"
5 sử dụng tiền tố để xác định hệ thống số. Tất cả các tiền tố số nguyên đều ở dạng >>> binary = 0b1010
>>> hexadecimal = "0xa"
6, trong đó bạn thay thế >>> binary = 0b1010
>>> hexadecimal = "0xa"
7 bằng ký tự đề cập đến hệ thống số:B: nhị phân [cơ sở 2]
>>>
>>> int["0x12F", base=16]
303
Lưu ý rằng
>>> binary = 0b1010
>>> hexadecimal = "0xa"
4 và >>> binary = 0b1010
>>> hexadecimal = "0xa"
5 sử dụng tiền tố để xác định hệ thống số. Tất cả các tiền tố số nguyên đều ở dạng >>> binary = 0b1010
>>> hexadecimal = "0xa"
6, trong đó bạn thay thế >>> binary = 0b1010
>>> hexadecimal = "0xa"
7 bằng ký tự đề cập đến hệ thống số:B: nhị phân [cơ sở 2]
O: Octal [cơ sở 8]
D: thập phân [cơ sở 10]
>>>
>>> str[10]
'10'
>>> type[str[10]]
Lưu ý rằng
>>> binary = 0b1010
>>> hexadecimal = "0xa"
4 và >>> binary = 0b1010
>>> hexadecimal = "0xa"
5 sử dụng tiền tố để xác định hệ thống số. Tất cả các tiền tố số nguyên đều ở dạng >>> binary = 0b1010
>>> hexadecimal = "0xa"
6, trong đó bạn thay thế >>> binary = 0b1010
>>> hexadecimal = "0xa"
7 bằng ký tự đề cập đến hệ thống số:>>>
Lưu ý rằng>>> binary = 0b1010
>>> hexadecimal = "0xa"
4 và >>> binary = 0b1010
>>> hexadecimal = "0xa"
5 sử dụng tiền tố để xác định hệ thống số. Tất cả các tiền tố số nguyên đều ở dạng >>> binary = 0b1010
>>> hexadecimal = "0xa"
6, trong đó bạn thay thế >>> binary = 0b1010
>>> hexadecimal = "0xa"
7 bằng ký tự đề cập đến hệ thống số:B: nhị phân [cơ sở 2]
O: Octal [cơ sở 8]
>>>
>>> octal = 0o1073
>>> f"{octal}" # Decimal
'571'
>>> f"{octal:x}" # Hexadecimal
'23b'
>>> f"{octal:b}" # Binary
'1000111011'
Lưu ý rằng
>>> binary = 0b1010
>>> hexadecimal = "0xa"
4 và >>> binary = 0b1010
>>> hexadecimal = "0xa"
5 sử dụng tiền tố để xác định hệ thống số. Tất cả các tiền tố số nguyên đều ở dạng >>> binary = 0b1010
>>> hexadecimal = "0xa"
6, trong đó bạn thay thế >>> binary = 0b1010
>>> hexadecimal = "0xa"
7 bằng ký tự đề cập đến hệ thống số:B: nhị phân [cơ sở 2]
O: Octal [cơ sở 8]
D: thập phân [cơ sở 10]
- X: Hexadecimal [cơ sở 16]
- Bây giờ bạn có một số kiến thức nền tảng về cách thể hiện số nguyên bằng cách sử dụng ____10 và
int
, bạn sẽ học cách chuyển đổi chuỗi trăn thànhint
. - Chuyển đổi chuỗi Python thành
int
- Nếu bạn có số nguyên thập phân được biểu thị dưới dạng chuỗi và bạn muốn chuyển đổi chuỗi Python thành
int
, thì bạn chỉ cần chuyển chuỗi thành
3, trả về số nguyên thập phân:>>> int["10"] 10 >>> type[int["10"]]
Theo mặc định,
>>> int["10"]
10
>>> type[int["10"]]
3 giả định rằng đối số chuỗi đại diện cho một số nguyên thập phân. Tuy nhiên, nếu bạn chuyển một chuỗi thập lục phân sang >>> int["10"]
10
>>> type[int["10"]]
3, thì bạn sẽ thấy một >>> int["10"]
10
>>> type[int["10"]]
6:Thông báo lỗi nói rằng chuỗi không phải là số nguyên thập phân hợp lệ. This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Convert a Python String to int