Hướng dẫn convert string to int if possible python - chuyển đổi chuỗi thành int nếu có thể python

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:

  1. Kết thúc cuộc gọi đến lớp int[] trong khối try/except.
  2. Nếu chuyển đổi thành công, khối try sẽ chạy hoàn toàn.
  3. Nếu chuyển đổi sang số nguyên bị lỗi, hãy xử lý
    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 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.

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ề

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 và chuỗi có thể được chuyển đổi thành một số nguyên.

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

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
2.

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!

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
2 để kiểm tra xem một chuỗi có thể được chuyển đổi thành số nguyên, ví dụ:

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
4. Nếu phương thức

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
5 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, 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

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
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.

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

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']
3.

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

Có thể chuyển đổi bất kỳ chuỗi nào thành số nguyên trong Python không?

Để chuyển đổi hoặc đúc, một chuỗi thành một số nguyên trong Python, bạn sử dụng hàm tích hợp int []. Hàm nhận được như một tham số, chuỗi ban đầu bạn muốn chuyển đổi và trả về số nguyên tương đương với giá trị bạn đã vượt qua. Cú pháp chung trông giống như thế này: int ["str"].you use the int[] built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int["str"] .

Bạn có thể chuyển đổi chuỗi thành INT không?

Sử dụng Integer.ParseInt [] để chuyển đổi chuỗi thành số nguyên Phương thức này trả về chuỗi dưới dạng loại nguyên thủy int.Nếu chuỗi không chứa một số nguyên hợp lệ thì nó sẽ ném một con sốFormatException. This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.

Điều gì xảy ra nếu bạn chuyển đổi chuỗi thành int python?

Trong khi chuyển đổi từ chuỗi sang INT, bạn có thể nhận được ngoại lệ ValueError.Ngoại lệ này xảy ra nếu chuỗi bạn muốn chuyển đổi không đại diện cho bất kỳ số nào.Giả sử, bạn muốn chuyển đổi một số thập lục phân thành một số nguyên.Nhưng bạn đã không vượt qua Base Agunce = 16 trong hàm int [].you may get ValueError exception. This exception occurs if the string you want to convert does not represent any numbers. Suppose, you want to convert a hexadecimal number to an integer. But you did not pass argument base=16 in the int[] function.

Làm thế nào để bạn kiểm tra xem một chuỗi là INT trong Python?

Python cung cấp phương thức isnumeric [] kiểm tra xem một chuỗi có phải là số nguyên hay không.Phương pháp này tương tự như phương thức isDigit [] nhưng với một vài khác biệt.Phương thức isNumeric [] kiểm tra xem tất cả các ký tự trong chuỗi là số.Trong khi phương thức isDigit [] kiểm tra xem các chuỗi chỉ chứa các chữ số.isnumeric[] method that checks whether a string is an integer or not. This method is similar to the isdigit[] method but with a few differences. The isnumeric[] method checks whether all the characters in the string are numeric. While the isdigit[] method checks whether the strings contain only digits.

Bài Viết Liên Quan

Chủ Đề