Hướng dẫn check if string is number in python - kiểm tra xem chuỗi có phải là số trong python không

Phương thức chuỗi


Thí dụ

Kiểm tra xem tất cả các ký tự trong văn bản là số:

TXT = "565543"

x = txt.isnumeric ()

in (x)

Hãy tự mình thử »


Định nghĩa và cách sử dụng

Phương thức

>>> float('NaN')
nan
1 trả về đúng nếu tất cả các ký tự là số (0-9), nếu không thì sai.

Số mũ, như ² và ¾ cũng được coi là giá trị số.

>>> float('NaN')
nan
2 và
>>> float('NaN')
nan
3 không được coi là giá trị số, bởi vì tất cả các ký tự trong chuỗi phải là số và
>>> float('NaN')
nan
4 và
>>> float('NaN')
nan
5 thì không.


Cú pháp

Giá trị tham số

Không có tham số.


Nhiều ví dụ hơn

Thí dụ

Kiểm tra xem các ký tự có phải là số không:

a = "\ u0030" #Unicode cho 0b = "\ u00b2" #Unicode for & sup2; C = "10km2" d = "-1" e = "1,5"
b = "\u00B2" #unicode for ²
c = "10km2"
d = "-1"
e = "1.5"

in (a.isnumeric ()) in (b.isnumeric ()) in (c.isNumeric ()) in (d.isNumeric ()) in (e.isNumeric ())
print(b.isnumeric())
print(c.isnumeric())
print(d.isnumeric())
print(e.isnumeric())

Hãy tự mình thử »


Phương thức chuỗi


Đối với số nguyên không âm (không dấu), hãy sử dụng

>>> float('NaN')
nan
6:

>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False

Tài liệu cho

>>> float('NaN')
nan
6: Python2, Python3

Đối với chuỗi Python 2 Unicode:

>>> float('NaN')
nan
1.

Hướng dẫn check if string is number in python - kiểm tra xem chuỗi có phải là số trong python không

Mateen Ulhaq

22.7K16 Huy hiệu vàng88 Huy hiệu bạc128 Huy hiệu đồng16 gold badges88 silver badges128 bronze badges

Đã trả lời ngày 9 tháng 12 năm 2008 lúc 20:15Dec 9, 2008 at 20:15

Hướng dẫn check if string is number in python - kiểm tra xem chuỗi có phải là số trong python không

17

Mà, không chỉ xấu và chậm

Tôi đang tranh chấp cả hai.

Một phương pháp phân tích cú pháp chuỗi hoặc chuỗi khác sẽ xấu hơn và chậm hơn.

Tôi không chắc rằng bất cứ điều gì có thể nhanh hơn ở trên. Nó gọi hàm và trả về. Try/Catch không giới thiệu nhiều chi phí vì ngoại lệ phổ biến nhất được bắt gặp mà không cần tìm kiếm rộng rãi các khung ngăn xếp.

Vấn đề là bất kỳ hàm chuyển đổi số nào cũng có hai loại kết quả

  • Một số, nếu số là hợp lệ
  • Mã trạng thái (ví dụ: thông qua ERRNO) hoặc ngoại lệ để hiển thị rằng không có số hợp lệ nào có thể được phân tích cú pháp.

C (ví dụ) hack xung quanh điều này một số cách. Python đưa nó ra rõ ràng và rõ ràng.

Tôi nghĩ rằng mã của bạn để làm điều này là hoàn hảo.

Hướng dẫn check if string is number in python - kiểm tra xem chuỗi có phải là số trong python không

Alec

7.6508 Huy hiệu vàng31 Huy hiệu bạc60 Huy hiệu Đồng8 gold badges31 silver badges60 bronze badges

Đã trả lời ngày 9 tháng 12 năm 2008 lúc 20:30Dec 9, 2008 at 20:30

S.LottS.LottS.Lott

378K79 Huy hiệu vàng503 Huy hiệu bạc773 Huy hiệu Đồng79 gold badges503 silver badges773 bronze badges

12

TL; dr Giải pháp tốt nhất là

>>> float('NaN')
nan
9 The best solution is
>>> float('NaN')
nan
9

Tôi đã thực hiện một số điểm chuẩn so sánh các phương pháp khác nhau

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()

Nếu chuỗi không phải là một số, khối ngoại trừ khá chậm. Nhưng quan trọng hơn, phương pháp Excet Try-Except là cách tiếp cận duy nhất xử lý các ký hiệu khoa học một cách chính xác.

funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)

Ký hiệu float ".1234" không được hỗ trợ bởi: - is_number_regex
- is_number_regex

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)

Ký hiệu khoa học "1.000000E+50" không được hỗ trợ bởi: - IS_NUMBER_REGEX - IS_NUMBER_REPL_ISDIGIT Ký hiệu khoa học "1E50" không được hỗ trợ bởi: - IS_NUMBER_REGEX - IS_NUMBER_REPL_ISDIGIT
- is_number_regex
- is_number_repl_isdigit
Scientific notation "1e50" is not supported by:
- is_number_regex
- is_number_repl_isdigit

Chỉnh sửa: Kết quả điểm chuẩn

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))

nơi các chức năng sau đã được kiểm tra

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()

Hướng dẫn check if string is number in python - kiểm tra xem chuỗi có phải là số trong python không

Idok

3.2444 Huy hiệu vàng19 Huy hiệu bạc18 Huy hiệu đồng4 gold badges19 silver badges18 bronze badges

Đã trả lời ngày 13 tháng 5 năm 2014 lúc 19:28May 13, 2014 at 19:28

14

Có một ngoại lệ mà bạn có thể muốn tính đến: Chuỗi 'nan'

Nếu bạn muốn is_number trả về sai cho 'nan', mã này sẽ không hoạt động khi Python chuyển đổi nó thành biểu diễn của nó không phải là số (nói về các vấn đề về nhận dạng):

>>> float('NaN')
nan

Nếu không, tôi thực sự nên cảm ơn bạn vì đoạn mã tôi hiện đang sử dụng rộng rãi. :)

G.

Đã trả lời ngày 1 tháng 9 năm 2010 lúc 14:06Sep 1, 2010 at 14:06

W7GVRW7GVRW7GVR

1.9131 Huy hiệu vàng18 Huy hiệu bạc24 Huy hiệu đồng1 gold badge18 silver badges24 bronze badges

4

Còn cái này thì sao:

'3.14'.replace('.','',1).isdigit()

sẽ trả về đúng chỉ khi có một hoặc không '.' Trong chuỗi các chữ số.

'3.14.5'.replace('.','',1).isdigit()

sẽ trả về sai

Chỉnh sửa: Chỉ cần thấy một nhận xét khác ... thêm

'3.14'.replace('.','',1).isdigit()
0 cho các trường hợp khác có thể được thực hiện. Nếu bạn đang vượt qua muối và không phải là gia vị tùy ý (ref: xkcd#974) Điều này sẽ tốt: P

David c

6,9544 Huy hiệu vàng48 Huy hiệu bạc65 Huy hiệu Đồng4 gold badges48 silver badges65 bronze badges

Đã trả lời ngày 25 tháng 5 năm 2012 lúc 22:22May 25, 2012 at 22:22

Haxwithaxehaxwithaxehaxwithaxe

8157 Huy hiệu bạc5 Huy hiệu Đồng7 silver badges5 bronze badges

5

Được cập nhật sau khi Alfe chỉ ra, bạn không cần kiểm tra nổi riêng như xử lý phức tạp cả hai:

def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True

Trước đây đã nói: Một số trường hợp hiếm hoi bạn cũng có thể cần kiểm tra các số phức tạp (ví dụ: 1+2i), không thể được biểu thị bằng một chiếc phao:

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
0

5

Mà, không chỉ là xấu xí và chậm, có vẻ cồng kềnh.

Nó có thể mất một số làm quen, nhưng đây là cách làm pythonic. Như đã được chỉ ra, các lựa chọn thay thế là tồi tệ hơn. Nhưng có một lợi thế khác của việc làm theo cách này: đa hình.

Ý tưởng trung tâm đằng sau việc đánh máy vịt là "nếu nó đi bộ và nói chuyện như một con vịt, thì đó là một con vịt." Điều gì sẽ xảy ra nếu bạn quyết định rằng bạn cần phải phân lớp chuỗi con để bạn có thể thay đổi cách bạn xác định xem có thể chuyển đổi một cái gì đó thành một chiếc phao? Hoặc nếu bạn quyết định kiểm tra một số đối tượng khác hoàn toàn? Bạn có thể làm những điều này mà không cần phải thay đổi mã trên.

Các ngôn ngữ khác giải quyết các vấn đề này bằng cách sử dụng giao diện. Tôi sẽ lưu phân tích giải pháp nào tốt hơn cho một chủ đề khác. Tuy nhiên, vấn đề là Python được quyết định ở phía bên của phương trình, và có lẽ bạn sẽ phải làm quen với cú pháp như thế này nếu bạn có kế hoạch lập trình nhiều trong Python (nhưng điều đó không có nghĩa là Bạn phải thích nó tất nhiên).

Một điều khác mà bạn có thể muốn xem xét: Python khá nhanh trong việc ném và bắt các ngoại lệ so với nhiều ngôn ngữ khác (ví dụ nhanh hơn 30 lần so với .NET). Heck, chính ngôn ngữ thậm chí còn ném các ngoại lệ để truyền đạt các điều kiện chương trình không ngoại trừ, bình thường (mỗi khi bạn sử dụng một vòng lặp). Vì vậy, tôi sẽ không lo lắng quá nhiều về các khía cạnh hiệu suất của mã này cho đến khi bạn nhận thấy một vấn đề đáng kể.

Đã trả lời ngày 11 tháng 12 năm 2008 lúc 4:56Dec 11, 2008 at 4:56

Jason Bakerjason BakerJason Baker

187K134 Huy hiệu vàng370 Huy hiệu bạc510 Huy hiệu Đồng134 gold badges370 silver badges510 bronze badges

3

Đối với

'3.14'.replace('.','',1).isdigit()
1, hãy sử dụng điều này:

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
1

Nhưng đối với

'3.14'.replace('.','',1).isdigit()
2, chúng tôi cần một số thủ thuật ;-). Mỗi số float đều có một điểm ...

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
2

Ngoài ra đối với các số âm, chỉ cần thêm

'3.14'.replace('.','',1).isdigit()
3:

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
3

Và bây giờ chúng ta có được một cách phổ quát:

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
4

Đã trả lời ngày 8 tháng 9 năm 2015 lúc 8:42Sep 8, 2015 at 8:42

SdwdawsdwdawSdwdaw

1.0197 Huy hiệu bạc14 Huy hiệu đồng7 silver badges14 bronze badges

3

Câu trả lời này cung cấp hướng dẫn từng bước có chức năng với các ví dụ để tìm chuỗi là:

  • Sô nguyên dương
  • Tích cực/Tiêu cực - Số nguyên/Float
  • Làm thế nào để loại bỏ các chuỗi "nan" (không phải số) trong khi kiểm tra số?

Kiểm tra xem chuỗi có số nguyên dương không

Bạn có thể sử dụng

'3.14'.replace('.','',1).isdigit()
4 để kiểm tra xem chuỗi đã cho có số nguyên dương hay không.
'3.14'.replace('.','',1).isdigit()
4
to check whether given string is positive integer.

Kết quả mẫu:

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
5

Kiểm tra chuỗi là dương/âm - số nguyên/float

'3.14'.replace('.','',1).isdigit()
4 Trả về
'3.14'.replace('.','',1).isdigit()
6 Nếu chuỗi là số âm hoặc số float. Ví dụ:

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
6

Nếu bạn cũng muốn kiểm tra các số nguyên âm và

'3.14'.replace('.','',1).isdigit()
2, thì bạn có thể viết một chức năng tùy chỉnh để kiểm tra nó như:also check for the negative integers and
'3.14'.replace('.','',1).isdigit()
2
, then you may write a custom function to check for it as:

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
7

Chạy mẫu:

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
8

Loại bỏ "nan" (không phải số) chuỗi trong khi kiểm tra số

Các chức năng trên sẽ trả về

'3.14'.replace('.','',1).isdigit()
8 cho chuỗi "NAN" (không phải là số) vì đối với Python, nó là float hợp lệ đại diện cho nó không phải là một số. Ví dụ:

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
9

Để kiểm tra xem số đó là "NAN", bạn có thể sử dụng

'3.14'.replace('.','',1).isdigit()
9 như:
'3.14'.replace('.','',1).isdigit()
9
as:

funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)
0

Hoặc nếu bạn không muốn nhập thư viện bổ sung để kiểm tra điều này, thì bạn có thể chỉ cần kiểm tra nó thông qua việc so sánh nó bằng chính nó bằng cách sử dụng

'3.14.5'.replace('.','',1).isdigit()
0. Python trả về
'3.14'.replace('.','',1).isdigit()
6 khi
'3.14.5'.replace('.','',1).isdigit()
2 nổi được so sánh với chính nó. Ví dụ:

funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)
1

Do đó, hàm trên

'3.14.5'.replace('.','',1).isdigit()
3 có thể được cập nhật để trả về
'3.14'.replace('.','',1).isdigit()
6 cho
'3.14.5'.replace('.','',1).isdigit()
5 như:function
'3.14.5'.replace('.','',1).isdigit()
3 can be updated to return
'3.14'.replace('.','',1).isdigit()
6 for
'3.14.5'.replace('.','',1).isdigit()
5
as:

funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)
2

Chạy mẫu:

funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)
3

Loại bỏ "nan" (không phải số) chuỗi trong khi kiểm tra số

Các chức năng trên sẽ trả về

'3.14'.replace('.','',1).isdigit()
8 cho chuỗi "NAN" (không phải là số) vì đối với Python, nó là float hợp lệ đại diện cho nó không phải là một số. Ví dụ:Feb 11, 2018 at 8:34

Hướng dẫn check if string is number in python - kiểm tra xem chuỗi có phải là số trong python không

Để kiểm tra xem số đó là "NAN", bạn có thể sử dụng

'3.14'.replace('.','',1).isdigit()
9 như:Moinuddin Quadri

Hoặc nếu bạn không muốn nhập thư viện bổ sung để kiểm tra điều này, thì bạn có thể chỉ cần kiểm tra nó thông qua việc so sánh nó bằng chính nó bằng cách sử dụng

'3.14.5'.replace('.','',1).isdigit()
0. Python trả về
'3.14'.replace('.','',1).isdigit()
6 khi
'3.14.5'.replace('.','',1).isdigit()
2 nổi được so sánh với chính nó. Ví dụ:12 gold badges94 silver badges121 bronze badges

Do đó, hàm trên

'3.14.5'.replace('.','',1).isdigit()
3 có thể được cập nhật để trả về
'3.14'.replace('.','',1).isdigit()
6 cho
'3.14.5'.replace('.','',1).isdigit()
5 như:

funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)
2


funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)
4
funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)
5

PS: Mỗi thao tác cho mỗi kiểm tra tùy thuộc vào loại số đi kèm với chi phí bổ sung. Chọn phiên bản của hàm

'3.14.5'.replace('.','',1).isdigit()
3 phù hợp với yêu cầu của bạn.

  • Đã trả lời ngày 11 tháng 2 năm 2018 lúc 8:34
  • Moinuddin Quadrimoinuddin Quadri
  • 45.1K12 Huy hiệu vàng94 Huy hiệu bạc121 Huy hiệu đồng

Đối với các chuỗi của những người không phải là số,

'3.14.5'.replace('.','',1).isdigit()
7 thực sự chậm hơn các biểu thức thông thường. Đối với các chuỗi có số hợp lệ, Regex chậm hơn. Vì vậy, phương pháp thích hợp phụ thuộc vào đầu vào của bạn.Aug 14, 2014 at 3:34

Nếu bạn thấy rằng bạn đang ở trong một ràng buộc hiệu suất, bạn có thể sử dụng một mô-đun bên thứ ba mới có tên FastNumbers cung cấp một chức năng gọi là ISFloat. Tiết lộ đầy đủ, tôi là tác giả. Tôi đã bao gồm kết quả của nó trong các thời gian dưới đây.SethMMorton

43K12 Huy hiệu vàng64 Huy hiệu bạc82 Huy hiệu Đồng12 gold badges64 silver badges82 bronze badges

6

Tôi biết điều này đặc biệt cũ nhưng tôi sẽ thêm một câu trả lời, tôi tin rằng bao gồm thông tin còn thiếu từ câu trả lời được bỏ phiếu cao nhất có thể rất có giá trị đối với bất kỳ ai tìm thấy điều này:

Đối với mỗi phương thức sau kết nối chúng với số lượng nếu bạn cần bất kỳ đầu vào nào được chấp nhận. (Giả sử chúng ta đang sử dụng các định nghĩa giọng hát của các số nguyên hơn là 0-255, v.v.)

def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True
0 hoạt động tốt để kiểm tra xem X có phải là số nguyên không.

def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True
1 hoạt động tốt để kiểm tra xem x có âm không. (Kiểm tra - ở vị trí đầu tiên)

def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True
2 hoạt động tốt để kiểm tra xem x là số thập phân.

def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True
3 hoạt động tốt để kiểm tra xem X có phải là tỷ lệ không.

def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True
4 hoạt động tốt để kiểm tra xem X có phải là một phần không.

Đã trả lời ngày 5 tháng 1 năm 2016 lúc 15:21Jan 5, 2016 at 15:21

AruthawolfaruthawolfAruthawolf

2812 Huy hiệu bạc12 Huy hiệu Đồng2 silver badges12 bronze badges

2

Chỉ bắt chước C#

Trong C# có hai hàm khác nhau xử lý phân tích các giá trị vô hướng:

  • Float.Parse()
  • Float.TryParse()

float.parse():

funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)
6

LƯU Ý: Nếu bạn đang tự hỏi tại sao tôi thay đổi ngoại lệ thành Kiểu hàng, đây là tài liệu.

float.try_parse():

funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)
7

Lưu ý: Bạn không muốn trả lại Boolean 'Sai' vì đó vẫn là loại giá trị. Không có gì tốt hơn vì nó chỉ ra thất bại. Tất nhiên, nếu bạn muốn một cái gì đó khác biệt, bạn có thể thay đổi tham số thất bại thành bất cứ điều gì bạn muốn.

Để mở rộng float để bao gồm 'parse ()' và 'try_parse ()', bạn sẽ cần phải đi bộ trong lớp 'float' để thêm các phương thức này.

Nếu bạn muốn tôn trọng các chức năng tồn tại trước, mã sẽ giống như:

funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)
8

Sidenote: Cá nhân tôi thích gọi nó là cú đấm khỉ vì cảm giác như tôi đang lạm dụng ngôn ngữ khi tôi làm điều này nhưng ymmv.

Usage:

funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)
9

Và Pythonas hiền triết vĩ đại nói với Holy See Sharpisus, "Bất cứ điều gì bạn có thể làm tôi có thể làm tốt hơn; tôi có thể làm bất cứ điều gì tốt hơn bạn."

Đã trả lời ngày 18 tháng 2 năm 2012 lúc 1:35Feb 18, 2012 at 1:35

Evan Plaitevan PlaiceEvan Plaice

Huy hiệu vàng 13,8K674 Huy hiệu bạc94 Huy hiệu đồng6 gold badges74 silver badges94 bronze badges

8

Đúc vào phao và bắt giá trị có lẽ là cách nhanh nhất, vì float () đặc biệt có nghĩa là chỉ cho điều đó. Bất cứ điều gì khác yêu cầu phân tích cú pháp chuỗi (Regex, v.v.) có thể sẽ chậm hơn do thực tế là nó không được điều chỉnh cho hoạt động này. 0,02 đô la của tôi.

Đã trả lời ngày 9 tháng 12 năm 2008 lúc 20:31Dec 9, 2008 at 20:31

CodelogicCodelogiccodelogic

70.4K9 Huy hiệu vàng58 Huy hiệu bạc54 Huy hiệu đồng9 gold badges58 silver badges54 bronze badges

3

Vì vậy, để kết hợp tất cả lại với nhau, kiểm tra các số NAN, Infinity và phức tạp (dường như chúng được chỉ định với J, không phải I, tức là 1+2J), nó dẫn đến:

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)
0

Đã trả lời ngày 23 tháng 3 năm 2012 lúc 16:10Mar 23, 2012 at 16:10

a1ana1ana1an

3.3565 huy hiệu vàng37 Huy hiệu bạc57 Huy hiệu đồng5 gold badges37 silver badges57 bronze badges

1

Tôi muốn xem phương pháp nào là nhanh nhất. Nhìn chung, kết quả tốt nhất và nhất quán nhất được đưa ra bởi hàm

def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True
5. Các kết quả nhanh nhất được đưa ra bởi hàm
def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True
6, nhưng chỉ khi không có ngoại lệ nào được bắn - nghĩa là mã của nó là hiệu quả nhất, nhưng chi phí ném ngoại lệ là khá lớn.

Xin lưu ý rằng việc kiểm tra diễn viên thành công là phương pháp duy nhất chính xác, ví dụ, điều này hoạt động với

def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True
6 nhưng hai chức năng thử nghiệm khác sẽ trả về false cho một chiếc phao hợp lệ:

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)
1

Đây là mã điểm chuẩn:

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)
2

Dưới đây là kết quả với Python 2.7.10 trên MacBook Pro 13: 2017

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)
3

Dưới đây là kết quả với Python 3.6.5 trên MacBook Pro 13: 2017

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)
4

Dưới đây là kết quả với Pypy 2.7.13 trên MacBook Pro 13: 2017

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)
5

Đã trả lời ngày 16 tháng 1 năm 2013 lúc 6:09Jan 16, 2013 at 6:09

Ron Reiterron ReiterRon Reiter

3.6903 Huy hiệu vàng29 Huy hiệu bạc33 Huy hiệu đồng3 gold badges29 silver badges33 bronze badges

2

Đầu vào có thể như sau:

def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True
8
def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True
9
def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
00
def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
01


Đầu vào 1 tổng hợp:

Đầu vào của chức năng này có thể là tất cả!

Tìm xem biến đã cho là số. Các chuỗi số bao gồm dấu hiệu tùy chọn, bất kỳ số chữ số nào, phần thập phân tùy chọn và phần hàm mũ tùy chọn. Do đó +0123.45E6 là một giá trị số hợp lệ. Hexadecimal (ví dụ: 0xF4C3B00C) và ký hiệu nhị phân (ví dụ: 0B10100111001) không được phép.

hàm is_numeric function

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)
6

test:

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)
7

hàm is_float function

Tìm xem biến đã cho là nổi. Chuỗi nổi bao gồm dấu hiệu tùy chọn, bất kỳ số chữ số nào, ...

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)
8

test:

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)
9

AST là gì?


2- Nếu bạn tự tin rằng nội dung biến là chuỗi:String:

sử dụng phương thức str.isdigit ()

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))
0

Đầu vào 3-Numerical:

phát hiện giá trị int:

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))
1

Phát hiện phao:

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))
2

Hướng dẫn check if string is number in python - kiểm tra xem chuỗi có phải là số trong python không

Bastian

8346 Huy hiệu bạc22 Huy hiệu Đồng6 silver badges22 bronze badges

Đã trả lời ngày 6 tháng 10 năm 2018 lúc 7:23Oct 6, 2018 at 7:23

3

Trong một trường hợp chung nhất cho một chiếc phao, người ta muốn chăm sóc các số nguyên và số thập phân. Hãy lấy chuỗi

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
02 làm ví dụ.

Tôi sẽ thử một trong những điều sau đây:

1.> isnumeric ()

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))
3

2.> isDigit ()

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))
4

3.> isdecimal ()

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))
5

Speed:

► Tất cả các phương pháp nói trên đều có tốc độ tương tự.

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))
6

Đã trả lời ngày 6 tháng 12 năm 2020 lúc 3:31Dec 6, 2020 at 3:31

Hướng dẫn check if string is number in python - kiểm tra xem chuỗi có phải là số trong python không

3

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
03

Trả về

'3.14'.replace('.','',1).isdigit()
8 Nếu tất cả các ký tự trong chuỗi là ký tự số và có ít nhất một ký tự,
'3.14'.replace('.','',1).isdigit()
6 nếu không. Các ký tự số bao gồm các ký tự chữ số và tất cả các ký tự có thuộc tính giá trị số Unicode, ví dụ: U+2155, phân số thô một phần năm. Chính thức, các ký tự số là các ký tự có giá trị thuộc tính numeric_type = Digit, numeric_type = decimal hoặc numeric_type = numeric.

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
06

Trả về

'3.14'.replace('.','',1).isdigit()
8 Nếu tất cả các ký tự trong chuỗi là các ký tự thập phân và có ít nhất một ký tự,
'3.14'.replace('.','',1).isdigit()
6 nếu không. Các ký tự thập phân là các ký tự có thể được sử dụng để hình thành số trong cơ sở 10, ví dụ: U+0660, chữ số tiếng Ả Rập không. Chính thức là một ký tự thập phân là một nhân vật trong danh mục chung của Unicode.

Cả hai có sẵn cho các loại chuỗi từ Python 3.0.

Georgy

11.1k7 Huy hiệu vàng62 Huy hiệu bạc70 Huy hiệu đồng7 gold badges62 silver badges70 bronze badges

Đã trả lời ngày 15 tháng 4 năm 2020 lúc 21:48Apr 15, 2020 at 21:48

Zardoshtzardoshtzardosht

2.7652 huy hiệu vàng22 Huy hiệu bạc29 Huy hiệu đồng2 gold badges22 silver badges29 bronze badges

Tôi cần xác định xem một chuỗi được đúc thành các loại cơ bản (float, int, str, bool). Sau khi không tìm thấy bất cứ điều gì trên internet, tôi đã tạo ra điều này:

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))
7

Thí dụ

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))
8

Bạn có thể nắm bắt loại và sử dụng nó

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))
9

Đã trả lời ngày 3 tháng 7 năm 2014 lúc 17:12Jul 3, 2014 at 17:12

Astrodsgastrodsgastrodsg

Huy hiệu 611 Bạc1 Huy hiệu Đồng1 silver badge1 bronze badge

3

Tôi nghĩ rằng giải pháp của bạn là tốt, nhưng có một triển khai RegEXP chính xác.

Dường như có rất nhiều sự ghét bỏ của RegEXP đối với những câu trả lời mà tôi nghĩ là không chính đáng, RegEXP có thể được sạch sẽ và chính xác một cách hợp lý và nhanh chóng. Nó thực sự phụ thuộc vào những gì bạn đang cố gắng làm. Câu hỏi ban đầu là làm thế nào bạn có thể "kiểm tra xem một chuỗi có thể được biểu diễn dưới dạng số (float)" (theo tiêu đề của bạn). Có lẽ bạn sẽ muốn sử dụng giá trị số/float sau khi bạn đã kiểm tra xem nó có hợp lệ hay không, trong trường hợp đó, bạn cố gắng/ngoại trừ rất có ý nghĩa. Nhưng nếu, vì một số lý do, bạn chỉ muốn xác nhận rằng một chuỗi là một số thì một regex cũng hoạt động tốt, nhưng thật khó để hiểu chính xác. Tôi nghĩ rằng hầu hết các câu trả lời của Regex cho đến nay, chẳng hạn, không phân tích đúng các chuỗi mà không có phần số nguyên (chẳng hạn như ".7") là một sự nổi khi có liên quan đến Python. Và điều đó hơi khó để kiểm tra trong một regex duy nhất trong đó phần phân số không cần thiết. Tôi đã bao gồm hai Regex để hiển thị điều này.

Nó đưa ra câu hỏi thú vị về một "số" là gì. Bạn có bao gồm "INF" có giá trị như một chiếc phao trong Python không? Hoặc bạn có bao gồm các số là "số" nhưng có lẽ không thể được biểu diễn bằng python (chẳng hạn như các số lớn hơn float max).

Cũng có sự mơ hồ trong cách bạn phân tích các số. Ví dụ, những gì về "--20"? Đây có phải là một "số"? Đây có phải là một cách hợp pháp để đại diện cho "20"? Python sẽ cho phép bạn thực hiện "var = --20" và đặt nó thành 20 (mặc dù thực sự điều này là do nó coi nó là một biểu thức), nhưng float ("-20") không hoạt động.

Dù sao, không có thêm thông tin, đây là một regex mà tôi tin rằng bao gồm tất cả các int và floats khi Python phân tích chúng.

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
0

Một số ví dụ Giá trị kiểm tra:

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
1

Chạy mã điểm chuẩn trong câu trả lời của @ron-Reiter cho thấy Regex này thực sự nhanh hơn so với Regex thông thường và nhanh hơn nhiều trong việc xử lý các giá trị xấu so với ngoại lệ, điều này có ý nghĩa. Kết quả:

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
2

Đã trả lời ngày 10 tháng 5 năm 2019 lúc 21:15May 10, 2019 at 21:15

Hướng dẫn check if string is number in python - kiểm tra xem chuỗi có phải là số trong python không

1

Tôi đã làm một số bài kiểm tra tốc độ. Hãy nói rằng nếu chuỗi có khả năng là một số thì chiến lược thử/ngoại trừ là nhanh nhất có thể. Nếu chuỗi không có khả năng là một số và bạn quan tâm đến kiểm tra số nguyên '-'). Nếu bạn quan tâm để kiểm tra số float, bạn phải sử dụng Thử/ngoại trừ Code Whitout Escape.likely to be a number the try/except strategy is the fastest possible.If the string is not likely to be a number and you are interested in Integer check, it worths to do some test (isdigit plus heading '-'). If you are interested to check float number, you have to use the try/except code whitout escape.

Đã trả lời ngày 12 tháng 10 năm 2010 lúc 7:43Oct 12, 2010 at 7:43

FxiiifxiiiFxIII

3984 Huy hiệu bạc12 Huy hiệu đồng4 silver badges12 bronze badges

0

Ryann gợi ý

Nếu bạn muốn trả về sai cho NAN và INF, hãy thay đổi dòng thành x = float (s); Trả về (x == x) và (x - 1! = x). Điều này sẽ trả về đúng cho tất cả các phao ngoại trừ inf và nan

Nhưng điều này không hoàn toàn hoạt động, bởi vì đối với những chiếc phao đủ lớn,

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
09 trả về đúng. Ví dụ:
def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
10

Hướng dẫn check if string is number in python - kiểm tra xem chuỗi có phải là số trong python không

Đã trả lời ngày 29 tháng 7 năm 2013 lúc 14:08Jul 29, 2013 at 14:08

Philhphilhphilh

6365 Huy hiệu bạc19 Huy hiệu đồng5 silver badges19 bronze badges

Tôi đã giải quyết một vấn đề dẫn tôi đến chủ đề này, cụ thể là làm thế nào để chuyển đổi một bộ sưu tập dữ liệu thành chuỗi và số theo cách trực quan nhất. Tôi nhận ra sau khi đọc mã gốc rằng những gì tôi cần là khác nhau theo hai cách:

1 - Tôi muốn có một kết quả số nguyên nếu chuỗi đại diện cho một số nguyên

2 - Tôi muốn có một số hoặc kết quả chuỗi để dán vào cấu trúc dữ liệu

Vì vậy, tôi đã điều chỉnh mã gốc để tạo ra đạo hàm này:

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
3

Đã trả lời ngày 9 tháng 11 năm 2014 lúc 14:06Nov 9, 2014 at 14:06

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
4

Đã trả lời ngày 2 tháng 8 năm 2018 lúc 11:06Aug 2, 2018 at 11:06

xin.chenxin.chenxin.chen

8761 Huy hiệu vàng8 Huy hiệu bạc21 Huy hiệu đồng1 gold badge8 silver badges21 bronze badges

1

Mã này xử lý các số mũ, phao và số nguyên, wihtout bằng regex.

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
5

Hướng dẫn check if string is number in python - kiểm tra xem chuỗi có phải là số trong python không

Kobi

Huy hiệu vàng 133K4141 gold badges253 silver badges285 bronze badges

Đã trả lời ngày 16 tháng 12 năm 2018 lúc 7:12Dec 16, 2018 at 7:12

Hướng dẫn check if string is number in python - kiểm tra xem chuỗi có phải là số trong python không

Ravi Tanwarravi Tanwarravi tanwar

5805 Huy hiệu bạc16 Huy hiệu Đồng5 silver badges16 bronze badges

1

Đây là cách đơn giản của tôi để làm điều đó. Giả sử rằng tôi đang lặp qua một số chuỗi và tôi muốn thêm chúng vào một mảng nếu chúng trở thành số.

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
6

Thay thế myVar.apppend bằng bất kỳ hoạt động nào bạn muốn thực hiện với chuỗi nếu nó hóa ra là một số. Ý tưởng là cố gắng sử dụng thao tác float () và sử dụng lỗi đã trả lại để xác định xem chuỗi có phải là số hay không.

Đã trả lời ngày 16 tháng 7 năm 2009 lúc 17:45Jul 16, 2009 at 17:45

1

Tôi cũng đã sử dụng chức năng mà bạn đã đề cập, nhưng chẳng mấy chốc tôi nhận thấy rằng các chuỗi là "nan", "inf" và biến thể của nó được coi là số. Vì vậy, tôi đề xuất bạn đã cải thiện phiên bản chức năng của mình, sẽ trả về sai cho các loại đầu vào đó và sẽ không thất bại trong các biến thể "1E3":

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
7

Đã trả lời ngày 15 tháng 10 năm 2016 lúc 21:11Oct 15, 2016 at 21:11

MathfacMathfacmathfac

1961 Huy hiệu bạc8 Huy hiệu đồng1 silver badge8 bronze badges

Chức năng trợ giúp người dùng:

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
8

sau đó

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
9

Đã trả lời ngày 15 tháng 8 năm 2019 lúc 22:18Aug 15, 2019 at 22:18

1

>>> float('NaN')
nan
0

Đã trả lời ngày 3 tháng 4 năm 2020 lúc 14:39Apr 3, 2020 at 14:39

Amir Saniyanamir SaniyanAmir Saniyan

12.6K19 Huy hiệu vàng87 Huy hiệu bạc134 Huy hiệu đồng19 gold badges87 silver badges134 bronze badges