Hướng dẫn is string to float possible in python? - chuỗi có thể nổi trong 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ệ).

Show

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

Chúng ta có thể chuyển đổi một số nguyên hoặc chuỗi cụ thể thành các số điểm nổi bằng phương thức tích hợp Python gọi là float (). Phương thức float () lấy kiểu dữ liệu chuỗi hoặc số nguyên và chuyển đổi dữ liệu đã cho thành số điểm nổi.

Hàm nào chuyển đổi một chuỗi thành một float?

Hàm atof () chuyển đổi một chuỗi ký tự thành giá trị điểm nổi độ chính xác kép. Chuỗi đầu vào là một chuỗi các ký tự có thể được hiểu là giá trị số của loại trả về được chỉ định.

Điều gì xảy ra khi bạn gọi một chuỗi trên một chiếc phao trong Python?

Ví dụ

# defining strings in Python
s = 'Favtutor'
print(s)

s = "Favtutor"
print(s)

s = '''Favtutor'''
print(s)

# multi-line string
s = """Compile with
    Favtutor"""
print(s)

Đầu ra

Favtutor
Favtutor
Favtutor
Compile with
    Favtutor

Float () là hàm python tích hợp để chuyển đổi một số hoặc chuỗi thành giá trị float và trả về kết quả. Nếu nó thất bại đối với bất kỳ đầu vào không hợp lệ, thì một ngoại lệ thích hợp xảy ra.

Khi bạn lấy đầu vào của người dùng & nbsp; trong lập trình Python trong khi làm việc với các hoạt động đầu cuối hoặc tệp như đọc hoặc viết tệp, đầu vào là một đối tượng chuỗi. Mặc dù bạn yêu cầu giá trị điểm nổi, phương thức đầu vào trong Python sẽ tìm nạp đầu vào người dùng dưới dạng đối tượng chuỗi. Do đó, bạn phải chuyển đổi rõ ràng chuỗi thành giá trị dấu phẩy động để bạn có thể thực hiện các hoạt động cần thiết trên nó. Trước khi hiểu các phương pháp để chuyển đổi chuỗi thành nổi một cách rõ ràng, trước tiên chúng ta hãy xem qua các chuỗi và các loại dữ liệu nổi trong Python.

Ví dụ

a = 3.14
print(type(a))
print(a)

Đầu ra

6) Chuyển đổi chuỗi thành Float với các điểm thập phân được chỉ định

Nó thường là cần thiết để mang lại độ chính xác cho số lượng số 0 sau thập phân trong các giá trị điểm nổi. Trong các trường hợp như vậy, bạn có thể sử dụng phương thức float () để chuyển đổi một chuỗi thành giá trị float và sau đó sử dụng phương thức định dạng () để chỉ định số lượng điểm thập phân trong giá trị float. Cú pháp của phương thức định dạng được đưa ra dưới đây:

1) Sử dụng hàm float ()

Bạn có thể sử dụng hàm float () để chuyển đổi bất kỳ loại dữ liệu nào thành số điểm nổi. Phương pháp này chỉ chấp nhận một tham số. Nếu bạn không vượt qua bất kỳ đối số nào, thì phương thức trả về 0,0. Nếu chuỗi đầu vào chứa một đối số bên ngoài phạm vi của giá trị dấu phẩy động, sẽ được tạo ra.

Ví dụ

s = '10.123'
f = float(s)
print('Float Value =', f)

Đầu ra

Nếu chuỗi đầu vào chứa bất cứ thứ gì khác ngoài biểu diễn dấu phẩy động của một số, đầu ra sẽ là valueError. Hãy cho chúng tôi hiểu điều này chi tiết dưới đây.

2) Chuyển đổi chuỗi số bằng dấu phẩy thành đối tượng dấu phẩy động

Hãy xem xét rằng chuỗi đầu vào là 1,0.123 '. Như bạn có thể thấy, chuỗi chứa các số, nhưng nó cũng có dấu phẩy trong đó. Do đó, việc chuyển đổi loại chuỗi này thành một giá trị dấu phẩy động là rất khó khăn. Nếu bạn gọi trực tiếp phương thức float (), thì đầu ra sẽ gây ra lỗi.

Ví dụ

s = '1,0.123'
f = float(s)
print('Float Value =', f)

Đầu ra

ValueError: could not convert string to float: '1,0.123'

Nếu chuỗi đầu vào chứa bất cứ thứ gì khác ngoài biểu diễn dấu phẩy động của một số, đầu ra sẽ là valueError. Hãy cho chúng tôi hiểu điều này chi tiết dưới đây.

Ví dụ

s = '1,0.123'
f = float(s.replace(',',''))
print('Float Value =', f)

Đầu ra

Nếu chuỗi đầu vào chứa bất cứ thứ gì khác ngoài biểu diễn dấu phẩy động của một số, đầu ra sẽ là valueError. Hãy cho chúng tôi hiểu điều này chi tiết dưới đây.

2) Chuyển đổi chuỗi số bằng dấu phẩy thành đối tượng dấu phẩy động

Ví dụ

s = "2.41, 6.81, 3.9, 10.21, 62.0"
res = [float(value) for value in s.split(', ')]
print("The float list is : " + str(res))

Đầ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

Nếu chuỗi đầu vào chứa bất cứ thứ gì khác ngoài biểu diễn dấu phẩy động của một số, đầu ra sẽ là valueError. Hãy cho chúng tôi hiểu điều này chi tiết dưới đây.

2) Chuyển đổi chuỗi số bằng dấu phẩy thành đối tượng dấu phẩy động

Ví dụ

Đầu ra

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

Nếu chuỗi đầu vào chứa bất cứ thứ gì khác ngoài biểu diễn dấu phẩy động của một số, đầu ra sẽ là valueError. Hãy cho chúng tôi hiểu điều này chi tiết dưới đây.

2) Chuyển đổi chuỗi số bằng dấu phẩy thành đối tượng dấu phẩy động

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

Đầu ra

Nếu chuỗi đầu vào chứa bất cứ thứ gì khác ngoài biểu diễn dấu phẩy động của một số, đầu ra sẽ là valueError. Hãy cho chúng tôi hiểu điều này chi tiết dưới đây.

2) Chuyển đổi chuỗi số bằng dấu phẩy thành đối tượng dấu phẩy động

Hãy xem xét rằng chuỗi đầu vào là 1,0.123 '. Như bạn có thể thấy, chuỗi chứa các số, nhưng nó cũng có dấu phẩy trong đó. Do đó, việc chuyển đổi loại chuỗi này thành một giá trị dấu phẩy động là rất khó khăn. Nếu bạn gọi trực tiếp phương thức float (), thì đầu ra sẽ gây ra lỗi.

Bạn phải xóa tất cả các dấu phẩy khỏi chuỗi trước khi gọi hàm float () để giải quyết vấn đề này. Hãy xem ví dụ dưới đây để hiểu rõ hơn.

3) Chuyển đổi chuỗi thành danh sách nổi trong Python

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

Đầu ra

Conclusion 

Nếu chuỗi đầu vào chứa bất cứ thứ gì khác ngoài biểu diễn dấu phẩy động của một số, đầu ra sẽ là valueError. Hãy cho chúng tôi hiểu điều này chi tiết dưới đây.

Chuỗi có thể được chuyển đổi thành float không?

Chúng ta có thể chuyển đổi chuỗi thành float trong java bằng phương thức float.parseFloat (). parseFloat() method.

Tại sao tôi không thể chuyển đổi một chuỗi thành một chiếc phao trong Python?

Python "valueError: Không thể chuyển đổi chuỗi thành float" xảy ra khi chúng ta chuyển một chuỗi không thể chuyển đổi thành một float (ví dụ: một chuỗi trống hoặc một chuỗi chứa các ký tự) sang lớp float (). Để giải quyết lỗi, xóa tất cả các ký tự không cần thiết khỏi chuỗi.remove all unnecessary characters from the string.

Bạn có thể chuyển đổi chuỗi thành int hoặc float không?

Chúng ta có thể chuyển đổi một số nguyên hoặc chuỗi cụ thể thành các số điểm nổi bằng phương thức tích hợp Python gọi là float ().Phương thức float () lấy kiểu dữ liệu chuỗi hoặc số nguyên và chuyển đổi dữ liệu đã cho thành số điểm nổi.. The float() method takes string or integer data type and converts the given data into a floating-point number.

Hàm nào chuyển đổi một chuỗi thành một float?

Hàm atof () chuyển đổi một chuỗi ký tự thành giá trị điểm nổi độ chính xác kép.Chuỗi đầu vào là một chuỗi các ký tự có thể được hiểu là giá trị số của loại trả về được chỉ định.atof() function converts a character string to a double-precision floating-point value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.

Điều gì xảy ra khi bạn gọi một chuỗi trên một chiếc phao trong Python?

Float () là hàm python tích hợp để chuyển đổi một số hoặc chuỗi thành giá trị float và trả về kết quả.Nếu nó thất bại đối với bất kỳ đầu vào không hợp lệ, thì một ngoại lệ thích hợp xảy ra.converts a number or a string to a float value and returns the result. If it fails for any invalid input, then an appropriate exception occurs.