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[]
Kiểm tra xem một chuỗi có thể được chuyển đổi thành số nguyên trong python #
Để kiểm tra xem một chuỗi có thể được chuyển đổi thành số nguyên không:
- Kết thúc cuộc gọi đến lớp
int[]
trong khốitry/except
. - Nếu chuyển đổi thành công, khối
try
sẽ chạy hoàn toàn. - Nếu chuyển đổi sang số nguyên bị lỗi, hãy xử lý
0 trong khốidef 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[]
1.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[]
Copied!
def can_convert_to_int[string]: try: int[string] return True except ValueError: return False print[can_convert_to_int['1357']] # 👉️ True print[can_convert_to_int['-1357']] # 👉️ True print[can_convert_to_int['1.357']] # 👉️ False print[can_convert_to_int['ABC123']] # 👉️ False
Chúng tôi đã sử dụng một khối try/except
để kiểm tra xem một chuỗi có thể được chuyển đổi thành một số nguyên.
Nếu khối try
thành công, hàm trả về
4 và chuỗi có thể được chuyển đổi thành một số nguyên.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[]
Nếu gọi lớp int[]
với chuỗi không thành công,
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 sẽ được nâng lên và hàm trả 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[]
7.Sử dụng một tuyên bố try/except
theo cách này thường được gọi là "yêu cầu tha thứ hơn là sự cho phép".
Chúng tôi chuyển chuỗi đến lớp int[]
không biết liệu việc chuyển đổi có thành công hay không và nếu lỗi
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 được nêu ra, chúng tôi sẽ xử lý nó trong khối 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[]
1.Ngoài ra, bạn có thể sử dụng phương pháp
2.Copied!
def can_convert_to_int[string]: try: int[string] return True except ValueError: return False print[can_convert_to_int['1357']] # 👉️ True print[can_convert_to_int['-1357']] # 👉️ True print[can_convert_to_int['1.357']] # 👉️ False print[can_convert_to_int['ABC123']] # 👉️ False
Kiểm tra xem chuỗi có thể được chuyển đổi thành số nguyên bằng isDigit [] #
Sử dụng phương thức Copied! Copied!
2 để kiểm tra xem một chuỗi có thể được chuyển đổi thành số nguyên, ví dụ: def can_convert_to_int[string]:
try:
int[string]
return True
except ValueError:
return False
print[can_convert_to_int['1357']] # 👉️ True
print[can_convert_to_int['-1357']] # 👉️ True
print[can_convert_to_int['1.357']] # 👉️ False
print[can_convert_to_int['ABC123']] # 👉️ False
def can_convert_to_int[string]:
try:
int[string]
return True
except ValueError:
return False
print[can_convert_to_int['1357']] # 👉️ True
print[can_convert_to_int['-1357']] # 👉️ True
print[can_convert_to_int['1.357']] # 👉️ False
print[can_convert_to_int['ABC123']] # 👉️ False
4. Nếu phương thức 5 trả vềCopied!
def can_convert_to_int[string]: try: int[string] return True except ValueError: return False print[can_convert_to_int['1357']] # 👉️ True print[can_convert_to_int['-1357']] # 👉️ True print[can_convert_to_int['1.357']] # 👉️ False print[can_convert_to_int['ABC123']] # 👉️ False
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[]
4, thì tất cả các ký tự trong chuỗi là các chữ số và nó có thể được chuyển đổi thành một số nguyên.Copied!
my_str = '1357' if my_str.isdigit[]: my_int = int[my_str] print[my_int] # 👉️ 1357 print['✅ string can be converted to integer'] else: print['⛔️ string CANNOT be converted to integer']
Chúng tôi đã sử dụng phương thức
2 để kiểm tra xem một chuỗi có thể được chuyển đổi thành một số nguyên một cách an toàn.Copied!
def can_convert_to_int[string]: try: int[string] return True except ValueError: return False print[can_convert_to_int['1357']] # 👉️ True print[can_convert_to_int['-1357']] # 👉️ True print[can_convert_to_int['1.357']] # 👉️ False print[can_convert_to_int['ABC123']] # 👉️ False
Phương thức str.isdigit trả 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[]
4 Nếu tất cả các ký tự trong chuỗi là các chữ số và có ít nhất 1 ký tự, nếu không 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[]
7 được trả về.Phương thức kiểm tra xem tất cả các ký tự trong chuỗi là các chữ số, vì vậy nếu chuỗi có dấu trừ hoặc số thập phân, nó sẽ trả 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[]
7.Copied!
my_str = '-1357' if my_str.isdigit[]: my_int = int[my_str] print[my_int] print['✅ string can be converted to integer'] else: # 👇️ this runs print['⛔️ string CANNOT be converted to integer']
Nếu chuỗi của bạn có thể là một số nguyên âm, hãy sử dụng ví dụ try/except
thay vào đó, vì nó cũng bao gồm các số nguyên âm.
Nếu bạn chỉ muốn thử chuyển đổi chuỗi thành số nguyên và im lặng/bỏ qua
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 nếu chuyển đổi không thành công, hãy sử dụng câu lệnh 3.Copied!
my_str = '1357' if my_str.isdigit[]: my_int = int[my_str] print[my_int] # 👉️ 1357 print['✅ string can be converted to integer'] else: print['⛔️ string CANNOT be converted to integer']
Copied!
my_str = '2468' try: my_int = int[my_str] print[my_int] # 👉️ 2468 except ValueError: pass
Câu lệnh PASS không làm gì và được sử dụng khi bắt buộc phải có câu lệnh nhưng chương trình không yêu cầu hành động.
Copied!
class Employee: pass