Hướng dẫn check if string can be converted to int python - kiểm tra xem chuỗi có thể được chuyển đổi thành int python không

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()

Cách thứ năm để kiểm tra xem chuỗi đầu vào có phải là số nguyên hay không trong Python bằng cách sử dụng kết hợp bất kỳ hàm bất kỳ () và map () nào trong Python. Ở đây trong ví dụ trên, chúng tôi đã lấy đầu vào như một chuỗi là ‘SDSD. Và sau đó với sự trợ giúp của bất kỳ (), map () và isDigit () hàm, chúng tôi có kiểm tra python nếu chuỗi là số nguyên.five dominant ways to check if a given python string is an integer or not.

Vì vậy, không lãng phí bất cứ lúc nào, hãy để trực tiếp nhảy vào các cách để kiểm tra Python nếu chuỗi là số nguyên.

  • Một số cách ưu tú để kiểm tra python nếu chuỗi là số nguyên
  • 1. Kiểm tra xem Chuỗi được đưa ra hay đầu vào có phải là số nguyên hay không sử dụng hàm isnumeric
  • 2. Kiểm tra python nếu chuỗi là số nguyên bằng cách sử dụng xử lý ngoại lệ
  • 3. Kiểm tra python nếu chuỗi là số nguyên sử dụng hàm isDigit
  • 4. Kiểm tra python nếu chuỗi là số nguyên bằng cách sử dụng biểu thức thông thường
  • 5. Kiểm tra python nếu chuỗi là số nguyên bằng bất kỳ () & nbsp; và & nbsp; map () & nbsp; chức năng
  • Các ứng dụng kiểm tra python nếu chuỗi là số nguyên
  • Phải đọc
  • Kết luận: Kiểm tra python nếu chuỗi là số nguyên

  • hàm isnumeric
  • Xử lý ngoại lệ
  • hàm isdigit
  • Biểu hiện thông thườ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()
    
    8 and 
    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 functions

1. Kiểm tra xem Chuỗi được đưa ra hay đầu vào có phải là số nguyên hay không sử dụng hàm isnumeric

2. Kiểm tra python nếu chuỗi là số nguyên bằng cách sử dụng xử lý ngoại lệ

3. Kiểm tra python nếu chuỗi là số nguyên sử dụng hàm isDigit

4. Kiểm tra python nếu chuỗi là số nguyên bằng cách sử dụng biểu thức thông thường

5. Kiểm tra python nếu chuỗi là số nguyên bằng bất kỳ () & nbsp; và & nbsp; map () & nbsp; chức năng

string.isnumeric()

Các ứng dụng kiểm tra python nếu chuỗi là số nguyên

Phải đọc

Kết luận: Kiểm tra python nếu chuỗi là số nguyên

#1
s = '695444'
print(s.isnumeric())

#2
s = '\u00BD'
print(s.isnumeric())

#3
s='pythonpool65'
print(s.isnumeric())

#4
s = '5651'
if s.isnumeric():
   print('Integer')
else:
   print('Not an integer')

hàm isnumeric

True
True
False
Integer

Explanation::

Xử lý ngoại lệ

  • hàm isdigit we have initialized and declared a string s with value ‘69544’. After that, with the isnumeric() function, we checked if ‘69544’ is an integer or not. In this case, it is an integer so, and it returned ‘True.’
  • Biểu hiện thông thường‘\u00BD’. This ‘\u00BD’ is a Unicode value, and you can write the digit and numeric characters using Unicode in the program. So, it returns true.
  • Có thể sử dụng hàm python từ & nbsp; isnumeric () để kiểm tra xem một chuỗi có phải là số nguyên hay không. Isnumeric () là một hàm tích hợp. Nó trả về đúng nếu tất cả các ký tự là số, nếu không thì sai.
  • Lưu ý: Isnumeric không kiểm tra xem chuỗi có đại diện cho số nguyên hay không, nó sẽ kiểm tra xem tất cả các ký tự trong chuỗi là ký tự số. Nhưng & nbsp; ________ 21 & nbsp; vẫn trả về đúng.

Sử dụng phương pháp khác nhau là bạn muốn tránh những trường hợp này.This method of checking if the string is an integer in Python will not work in negative numbers.

2. Kiểm tra python nếu chuỗi là số nguyên bằng cách sử dụng xử lý ngoại lệ

3. Kiểm tra python nếu chuỗi là số nguyên sử dụng hàm isDigit

4. Kiểm tra python nếu chuỗi là số nguyên bằng cách sử dụng biểu thức thông thường

5. Kiểm tra python nếu chuỗi là số nguyên bằng bất kỳ () & nbsp; và & nbsp; map () & nbsp; chức năng

try: 
    # Code 
except: 
    # Code

Các ứng dụng kiểm tra python nếu chuỗi là số nguyên

Phải đọc

Kết luận: Kiểm tra python nếu chuỗi là số nguyên

s = '951sd'
isInt = True
try:
   # converting to integer
   int(s)
except ValueError:
   isInt = False
if isInt:
   print('Input value is an integer')
else:
   print('Not an integer')

hàm isnumeric

Not an integer

Explanation::

Xử lý ngoại lệ‘s’ is an integer. So we declared it true. After that, we Tried to convert string to an integer using 

string.isnumeric()
4 function.
If the string ‘s’ contains non-numeric characters, then ‘int’ will throw a ValueError, which will indicate that the string is not an integer and vice-versa.

hàm isdigit

Biểu hiện thông thườngThis method of checking if the string is an integer in Python will also work on Negative Numbers.

3. Kiểm tra python nếu chuỗi là số nguyên sử dụng hàm isDigit

4. Kiểm tra python nếu chuỗi là số nguyên bằng cách sử dụng biểu thức thông thườngisdigit() function to check if the string is an integer or not in Python. The isdigit() method returns True if all characters in a string are digits. Otherwise, it returns False.

4. Kiểm tra python nếu chuỗi là số nguyên bằng cách sử dụng biểu thức thông thường

Cú pháp

string.isdigit()

Thông số

Phương thức & nbsp; ____ 25 & nbsp; không có bất kỳ tham số nào.

Giá trị trả về của hàm isDigit ()

  • Trả về true - nếu tất cả các ký tự trong chuỗi là các chữ số.
  • Trả về FALSE-Nếu chuỗi chứa một hoặc nhiều chữ số

Ví dụ

str = input("Enter any value: ")

if str.isdigit():
    print("User input is an Integer ")
else:
    print("User input is string ")

Đầu ra

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

Explanation::

Ví dụ thứ ba để kiểm tra xem chuỗi đầu vào có phải là số nguyên đang sử dụng hàm isDigit () không. Ở đây trong ví dụ trên, chúng tôi đã lấy đầu vào từ chuỗi và lưu trữ nó trong biến 'str.' Sau đó, với sự trợ giúp của các câu lệnh điều khiển và hàm isDigit (), chúng tôi đã xác minh xem chuỗi đầu vào có phải là số nguyên hay không .

Lưu ý: Hàm ____ 26 ‘& nbsp; sẽ chỉ hoạt động cho các số nguyên dương. tức là, nếu bạn vượt qua bất kỳ số float nào, nó sẽ nói đó là một chuỗi. & nbsp; nó không lấy bất kỳ đối số nào, do đó nó trả về một lỗi nếu một tham số được truyền
The

string.isnumeric()
6‘ function will work only for positive integer numbers. i.e., if you pass any float number, it will say it is a string. 
It does not take any arguments, therefore it returns an error if a parameter is passed

4. Kiểm tra python nếu chuỗi là số nguyên bằng cách sử dụng biểu thức thông thường

Chúng ta có thể sử dụng mẫu tìm kiếm được gọi là biểu thức thông thường để kiểm tra xem một chuỗi có phải là số nguyên hay không trong Python. Nếu bạn không biết biểu thức chính quy là gì và cách thức hoạt động trong Python, hãy để tôi giải thích ngắn gọn cho bạn. Trong Python, một biểu thức chính quy là một chuỗi các ký tự cụ thể giúp có thể khớp hoặc tìm các chuỗi hoặc bộ chuỗi khác, với một cú pháp chuyên dụng được giữ ở một mẫu. Biểu thức thường xuyên được sử dụng rộng rãi trong thế giới Unix.

Ở đây chúng tôi đang sử dụng Phương thức khớp của biểu thức thông thường I.E, re.Match (). Re.Match () chỉ tìm kiếm trong dòng đầu tiên của chuỗi và trả về đối tượng đối tượng nếu tìm thấy, khác không trả về không. Nhưng nếu một trận đấu của chuỗi con được đặt trong một số dòng khác ngoài dòng chuỗi đầu tiên (trong trường hợp chuỗi nhiều dòng), nó sẽ không trả về không..
Re.match() searches only in the first line of the string and return match object if found, else return none. But if a match of substring is located in some other line aside from the first line of string (in case of a multi-line string), it returns none.

Hãy cùng xem qua một ví dụ về cách nó hoạt động.

Cú pháp

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

Thông số

  1. Phương thức & nbsp; ____ 25 & nbsp; không có bất kỳ tham số nào.
    It contains the regular expression that is to be matched.
  2. Giá trị trả về của hàm isDigit ()
    It comprises of the string that would be searched to match the pattern at the beginning of the string.
  3. Trả về true - nếu tất cả các ký tự trong chuỗi là các chữ số.
    You can specify different flags using bitwise OR (|). These are modifiers.

Trả về FALSE-Nếu chuỗi chứa một hoặc nhiều chữ số

  • Ví dụ
  • Đầu ra

Ví dụ

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()
2

Đầu ra

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()
3

Explanation::

Ví dụ thứ ba để kiểm tra xem chuỗi đầu vào có phải là số nguyên đang sử dụng hàm isDigit () không. Ở đây trong ví dụ trên, chúng tôi đã lấy đầu vào từ chuỗi và lưu trữ nó trong biến 'str.' Sau đó, với sự trợ giúp của các câu lệnh điều khiển và hàm isDigit (), chúng tôi đã xác minh xem chuỗi đầu vào có phải là số nguyên hay không .‘import re’. After that, we have taken input from the user and stored it in variable value. Then we have used our method re.match() to check if the input string is an integer or not. The pattern to be matched here is “[-+]?\d+$”. This pattern indicates that it will only match if we have our input string as an integer.

Lưu ý: Hàm ____ 26 ‘& nbsp; sẽ chỉ hoạt động cho các số nguyên dương. tức là, nếu bạn vượt qua bất kỳ số float nào, nó sẽ nói đó là một chuỗi. & nbsp; nó không lấy bất kỳ đối số nào, do đó nó trả về một lỗi nếu một tham số được truyền
The

string.isnumeric()
8‘ function will also work with negative numbers as well.

4. Kiểm tra python nếu chuỗi là số nguyên bằng cách sử dụng biểu thức thông thường

Chúng ta có thể sử dụng mẫu tìm kiếm được gọi là biểu thức thông thường để kiểm tra xem một chuỗi có phải là số nguyên hay không trong Python. Nếu bạn không biết biểu thức chính quy là gì và cách thức hoạt động trong Python, hãy để tôi giải thích ngắn gọn cho bạn. Trong Python, một biểu thức chính quy là một chuỗi các ký tự cụ thể giúp có thể khớp hoặc tìm các chuỗi hoặc bộ chuỗi khác, với một cú pháp chuyên dụng được giữ ở một mẫu. Biểu thức thường xuyên được sử dụng rộng rãi trong thế giới Unix.any() and map() function to check if a string is an integer or not in Python. If you don’t know what are any() and map() functions and how they work in python, let me briefly explain it to you.

  • Ở đây chúng tôi đang sử dụng Phương thức khớp của biểu thức thông thường I.E, re.Match (). Re.Match () chỉ tìm kiếm trong dòng đầu tiên của chuỗi và trả về đối tượng đối tượng nếu tìm thấy, khác không trả về không. Nhưng nếu một trận đấu của chuỗi con được đặt trong một số dòng khác ngoài dòng chuỗi đầu tiên (trong trường hợp chuỗi nhiều dòng), nó sẽ không trả về không.
  • Hãy cùng xem qua một ví dụ về cách nó hoạt động.

mẫu chứa biểu thức chính quy được khớp.

Cú pháp

Chuỗi bao gồm chuỗi sẽ được tìm kiếm để khớp với mẫu ở đầu chuỗ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()
4

Cờ (tùy chọn) Bạn có thể chỉ định các cờ khác nhau bằng bitwise hoặc (|). Đây là những sửa đổ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()
5

Thông số

Giá trị trả về Parameters

Trả về các đối tượng đối tượng nếu tìm thấy.
An iterable object (list, tuple, dictionary)

Nếu không có khớp, giá trị & nbsp; ____ 27 & nbsp; sẽ được trả về, thay vì đối tượng khớp.

Cách thứ tư để kiểm tra xem chuỗi đầu vào có phải là số nguyên hay không trong Python có sử dụng cơ chế biểu thức chính quy không. Ở đây trong ví dụ này, đầu tiên chúng tôi đã nhập biểu thức chính quy bằng cách sử dụng ‘nhập RE. Sau đó, chúng tôi đã lấy đầu vào từ người dùng và lưu trữ nó trong giá trị biến. Sau đó, chúng tôi đã sử dụng phương thức của chúng tôi re.match () để kiểm tra xem chuỗi đầu vào có phải là số nguyên hay không. Mẫu được khớp ở đây là [-+]? \ D+$. Mẫu này chỉ ra rằng nó sẽ chỉ khớp nếu chúng ta có chuỗi đầu vào của mình như một số nguyên.:
The function to execute for each item
iterable
A sequence, collection or an iterator object. You can send as many iterables as you like, just make sure the function has one parameter for each iterable.

Trả về FALSE-Nếu chuỗi chứa một hoặc nhiều chữ số

  • Ví dụany() function returns True if any item in an iterable is true, otherwise, it returns False.
  • Đầu ra

Ví dụ

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()
6

Đầu ra

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

Explanation::

Ví dụ thứ ba để kiểm tra xem chuỗi đầu vào có phải là số nguyên đang sử dụng hàm isDigit () không. Ở đây trong ví dụ trên, chúng tôi đã lấy đầu vào từ chuỗi và lưu trữ nó trong biến 'str.' Sau đó, với sự trợ giúp của các câu lệnh điều khiển và hàm isDigit (), chúng tôi đã xác minh xem chuỗi đầu vào có phải là số nguyên hay không .

Chúng tôi hiểu sai vì chuỗi đầu vào là SDSD.‘sdsd’.

Lưu ý: Phương pháp này cũng sẽ hoạt động với số âm.
This method will also work with negative numbers.

Các ứng dụng kiểm tra python nếu chuỗi là số nguyên

  • Để kiểm tra xem một biến hoặc giá trị chuỗi đã cho chỉ chứa các số nguyên như xác thực nếu người dùng nhập tùy chọn số chính xác vào ứng dụng dựa trên menu.
  • Sử dụng các giá trị ASCII của các ký tự, đếm và in tất cả các chữ số bằng hàm isDigit ().

Phải đọc

  • Giới thiệu về Super Python với các ví dụ
  • Chức năng giúp đỡ Python
  • Tại sao sython sys.exit tốt hơn các chức năng thoát khác?
  • Python bitstring: Các lớp học và các ví dụ khác | Mô -đun

Kết luận: Kiểm tra python nếu chuỗi là số nguyên

Vì vậy, nếu bạn làm cho đến cuối cùng, tôi khá chắc chắn rằng bây giờ bạn có thể hiểu tất cả các cách có thể để kiểm tra xem một chuỗi có số nguyên trong Python không. Cách tốt nhất có thể để kiểm tra xem chuỗi có phải là số nguyên trong Python phụ thuộc vào nhu cầu của bạn và loại dự án bạn đang làm. Tôi nghĩ rằng bạn cũng có thể muốn biết & nbsp; các cách trong Python để sắp xếp danh sách danh sách. Nếu có, có một hướng dẫn tuyệt vời có sẵn trong thư viện hướng dẫn của chúng tôi, hãy kiểm tra nó.

Vẫn có bất kỳ nghi ngờ hoặc câu hỏi nào cho tôi biết trong phần bình luận dưới đây. Tôi sẽ cố gắng giúp bạn càng sớm càng tốt.

Happy Pythoning!