Hướng dẫn how do you change a percent to a decimal in python? - làm cách nào để thay đổi phần trăm thành số thập phân trong python?

Tôi đã viết phương pháp sau đây luôn luôn trả lại đầu ra cho độ chính xác chính xác như đầu vào, không có lỗi điểm nổi như trong các câu trả lời khác.

def percent_to_float[s]:
    s = str[float[s.rstrip["%"]]]
    i = s.find["."]
    if i == -1:
        return int[s] / 100
    if s.startswith["-"]:
        return -percent_to_float[s.lstrip["-"]]
    s = s.replace[".", ""]
    i -= 2
    if i < 0:
        return float["." + "0" * abs[i] + s]
    else:
        return float[s[:i] + "." + s[i:]]

Giải trình

  1. Dải "%" từ cuối.
  2. Nếu phần trăm không có ".", Chỉ cần trả lại nó chia cho 100.
  3. Nếu phần trăm là âm, hãy loại bỏ chức năng "-" và gọi lại, sau đó chuyển đổi kết quả trở lại thành âm và trả lại.
  4. Loại bỏ vị trí thập phân.
  5. Giảm i [chỉ số vị trí thập phân ở mức] bởi 2, bởi vì chúng tôi muốn chuyển vị trí thập phân 2 không gian sang trái.
  6. Nếu i là âm, thì chúng ta cần phải đệm với số không.
    • Ví dụ: Giả sử đầu vào là "1,33%". Để có thể chuyển các khoảng trống ở vị trí số thập phân sang bên trái, chúng ta sẽ cần phải đệm bằng số không. Suppose the input is "1.33%". To be able to shift the decimal place 2 spaces to the left, we would need to pad with a zero.
  7. Chuyển đổi thành một chiếc phao.

Trường hợp kiểm tra [thử trực tuyến]:

from unittest.case import TestCase

class ParsePercentCase[TestCase]:
    tests = {
        "150%"              : 1.5,
        "100%"              : 1,
        "99%"               : 0.99,
        "99.999%"           : 0.99999,
        "99.5%"             : 0.995,
        "95%"               : 0.95,
        "90%"               : 0.9,
        "50%"               : 0.5,
        "66.666%"           : 0.66666,
        "42%"               : 0.42,
        "20.5%"             : 0.205,
        "20%"               : 0.2,
        "10%"               : 0.1,
        "3.141592653589793%": 0.03141592653589793,
        "1%"                : 0.01,
        "0.1%"              : 0.001,
        "0.01%"             : 0.0001,
        "0%"                : 0,
    }
    tests = sorted[tests.items[], key=lambda x: -x[1]]

    def test_parse_percent[self]:
        for percent_str, expected in self.tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]

    def test_parse_percent_negative[self]:
        negative_tests = [["-" + s, -f] for s, f in self.tests]
        for percent_str, expected in negative_tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]

Làm thế nào để bạn chuyển đổi một chuỗi đại diện cho một số phần trăm thành một số thực tế có thể được sử dụng để thực hiện các tính toán?

Để chuyển đổi một chuỗi được biểu diễn dưới dạng số phần trăm thành số thập phân thực tế trong Python, hãy sử dụng hàm ____10 tích hợp sau khi xóa ký hiệu phần trăm khỏi chuỗi và bất kỳ ký tự nào khác ngăn chặn chuyển đổi số.

Không cần thanh lọc từ chuỗi gốc, biểu tượng phần trăm bạn sẽ nhận được

from unittest.case import TestCase

class ParsePercentCase[TestCase]:
    tests = {
        "150%"              : 1.5,
        "100%"              : 1,
        "99%"               : 0.99,
        "99.999%"           : 0.99999,
        "99.5%"             : 0.995,
        "95%"               : 0.95,
        "90%"               : 0.9,
        "50%"               : 0.5,
        "66.666%"           : 0.66666,
        "42%"               : 0.42,
        "20.5%"             : 0.205,
        "20%"               : 0.2,
        "10%"               : 0.1,
        "3.141592653589793%": 0.03141592653589793,
        "1%"                : 0.01,
        "0.1%"              : 0.001,
        "0.01%"             : 0.0001,
        "0%"                : 0,
    }
    tests = sorted[tests.items[], key=lambda x: -x[1]]

    def test_parse_percent[self]:
        for percent_str, expected in self.tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]

    def test_parse_percent_negative[self]:
        negative_tests = [["-" + s, -f] for s, f in self.tests]
        for percent_str, expected in negative_tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]
1 như được trình bày bên dưới trong Python replin:

>>> float["30.0%"]
Traceback [most recent call last]:
File "", line 1, in
ValueError: could not convert string to f
loat: '30.0%'

Vì vậy, để có được sự chuyển đổi hoạt động tốt, bạn cần xóa các ký tự khỏi chuỗi ban đầu, điều này sẽ bao gồm biểu tượng phần trăm.

Dưới đây, một ví dụ chứng minh việc sử dụng chức năng float và cách bạn có thể sử dụng phương thức chuỗi

from unittest.case import TestCase

class ParsePercentCase[TestCase]:
    tests = {
        "150%"              : 1.5,
        "100%"              : 1,
        "99%"               : 0.99,
        "99.999%"           : 0.99999,
        "99.5%"             : 0.995,
        "95%"               : 0.95,
        "90%"               : 0.9,
        "50%"               : 0.5,
        "66.666%"           : 0.66666,
        "42%"               : 0.42,
        "20.5%"             : 0.205,
        "20%"               : 0.2,
        "10%"               : 0.1,
        "3.141592653589793%": 0.03141592653589793,
        "1%"                : 0.01,
        "0.1%"              : 0.001,
        "0.01%"             : 0.0001,
        "0%"                : 0,
    }
    tests = sorted[tests.items[], key=lambda x: -x[1]]

    def test_parse_percent[self]:
        for percent_str, expected in self.tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]

    def test_parse_percent_negative[self]:
        negative_tests = [["-" + s, -f] for s, f in self.tests]
        for percent_str, expected in negative_tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]
2 tích hợp để loại bỏ biểu tượng tỷ lệ phần trăm:

>>> float["30.0%".replace["%", ""]]
30.0

Như bạn có thể thấy từ ví dụ trên, bạn có thể trích xuất số từ chuỗi phần trăm ban đầu.

Bây giờ bạn có một số để chuyển đổi số phần trăm thành đại diện thập phân của nó chỉ đơn giản là chia cho 100.

Tại đây, cách bạn có thể viết ở trên trong một dòng mã nhỏ gọn:

>>> float["30.0%".replace["%", ""]]/100
0.3

Đây là cách dễ nhất để chuyển đổi số chuỗi bằng biểu tượng phần trăm.

Tuy nhiên, có thể có nhiều lần các nhân vật khác cần được xóa để giúp chuyển đổi.

Chuyển đổi số chuỗi phần trăm bằng dấu phẩy

Một ký tự khác có thể ngăn chặn việc chuyển đổi đúng số phần trăm là nếu chuỗi chứa dấu phẩy.

Ở đây, một ví dụ chứng minh chuyển đổi trước đó, nhưng sử dụng nó trên số phần trăm chuỗi với dấu phẩy, một lần nữa bạn sẽ nhận được

from unittest.case import TestCase

class ParsePercentCase[TestCase]:
    tests = {
        "150%"              : 1.5,
        "100%"              : 1,
        "99%"               : 0.99,
        "99.999%"           : 0.99999,
        "99.5%"             : 0.995,
        "95%"               : 0.95,
        "90%"               : 0.9,
        "50%"               : 0.5,
        "66.666%"           : 0.66666,
        "42%"               : 0.42,
        "20.5%"             : 0.205,
        "20%"               : 0.2,
        "10%"               : 0.1,
        "3.141592653589793%": 0.03141592653589793,
        "1%"                : 0.01,
        "0.1%"              : 0.001,
        "0.01%"             : 0.0001,
        "0%"                : 0,
    }
    tests = sorted[tests.items[], key=lambda x: -x[1]]

    def test_parse_percent[self]:
        for percent_str, expected in self.tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]

    def test_parse_percent_negative[self]:
        negative_tests = [["-" + s, -f] for s, f in self.tests]
        for percent_str, expected in negative_tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]
1 quá quen thuộc:

>>> float["3,000%".replace["%", ""]]
Traceback [most recent call last]:
File "", line 1, in
ValueError: could not convert string to float: '3,000.0'

Do đó, bên cạnh việc xóa biểu tượng

from unittest.case import TestCase

class ParsePercentCase[TestCase]:
    tests = {
        "150%"              : 1.5,
        "100%"              : 1,
        "99%"               : 0.99,
        "99.999%"           : 0.99999,
        "99.5%"             : 0.995,
        "95%"               : 0.95,
        "90%"               : 0.9,
        "50%"               : 0.5,
        "66.666%"           : 0.66666,
        "42%"               : 0.42,
        "20.5%"             : 0.205,
        "20%"               : 0.2,
        "10%"               : 0.1,
        "3.141592653589793%": 0.03141592653589793,
        "1%"                : 0.01,
        "0.1%"              : 0.001,
        "0.01%"             : 0.0001,
        "0%"                : 0,
    }
    tests = sorted[tests.items[], key=lambda x: -x[1]]

    def test_parse_percent[self]:
        for percent_str, expected in self.tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]

    def test_parse_percent_negative[self]:
        negative_tests = [["-" + s, -f] for s, f in self.tests]
        for percent_str, expected in negative_tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]
4 thực tế, nếu số phần trăm của bạn có chứa dấu phẩy, bạn cũng có thể cần phải xóa nó.

Rất may, nó không quá khó để xóa các ký tự bổ sung khỏi chuỗi ban đầu của bạn nhưng nếu bạn vẫn muốn sử dụng phương thức Chuỗi thay thế, bạn sẽ cần phải xâu chuỗi chúng lại với nhau như vậy:

>>> float["3,000%".replace["%", ""].replace[",", ""]]/100
30.0

Như bạn có thể thấy từ ví dụ trên, mã Python đầu ra kết quả dự định của

from unittest.case import TestCase

class ParsePercentCase[TestCase]:
    tests = {
        "150%"              : 1.5,
        "100%"              : 1,
        "99%"               : 0.99,
        "99.999%"           : 0.99999,
        "99.5%"             : 0.995,
        "95%"               : 0.95,
        "90%"               : 0.9,
        "50%"               : 0.5,
        "66.666%"           : 0.66666,
        "42%"               : 0.42,
        "20.5%"             : 0.205,
        "20%"               : 0.2,
        "10%"               : 0.1,
        "3.141592653589793%": 0.03141592653589793,
        "1%"                : 0.01,
        "0.1%"              : 0.001,
        "0.01%"             : 0.0001,
        "0%"                : 0,
    }
    tests = sorted[tests.items[], key=lambda x: -x[1]]

    def test_parse_percent[self]:
        for percent_str, expected in self.tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]

    def test_parse_percent_negative[self]:
        negative_tests = [["-" + s, -f] for s, f in self.tests]
        for percent_str, expected in negative_tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]
5 từ số chuỗi phần trăm chứa dấu phẩy.

Xóa tất cả các ký tự không phải là số

Một cách dễ dàng hơn để quản lý việc loại bỏ tất cả các ký tự có thể chứng minh có vấn đề với chuyển đổi chuỗi là chỉ xóa mọi thứ ngoại trừ các số và các ký tự vị trí thập phân.

Cách tốt nhất để xử lý loại hoạt động này là nhập thư viện biểu thức thông thường [Regex cho] và sử dụng chức năng thay thế.

Hàm thay thế có ba tham số với mẫu đầu tiên là mẫu regex phù hợp, tham số thứ hai để thay thế và thứ ba chuỗi hoạt động.

Ở đây, một cách bạn có thể loại bỏ tất cả các số bằng thư viện Regex:

>>> import re
>>> float[re.sub[r"[^0-9.]", "", "3,000.0%"]]/100
30.0

Từ mã trên, bạn có thể thấy thư viện Regex cần được nhập trước và sau đó bạn thực hiện thay thế tất cả các ký tự vị trí không phải là số và thập phân từ chuỗi phần trăm.

Mẫu regex xử lý điều này được nhìn thấy trong tham số đầu tiên của hàm

from unittest.case import TestCase

class ParsePercentCase[TestCase]:
    tests = {
        "150%"              : 1.5,
        "100%"              : 1,
        "99%"               : 0.99,
        "99.999%"           : 0.99999,
        "99.5%"             : 0.995,
        "95%"               : 0.95,
        "90%"               : 0.9,
        "50%"               : 0.5,
        "66.666%"           : 0.66666,
        "42%"               : 0.42,
        "20.5%"             : 0.205,
        "20%"               : 0.2,
        "10%"               : 0.1,
        "3.141592653589793%": 0.03141592653589793,
        "1%"                : 0.01,
        "0.1%"              : 0.001,
        "0.01%"             : 0.0001,
        "0%"                : 0,
    }
    tests = sorted[tests.items[], key=lambda x: -x[1]]

    def test_parse_percent[self]:
        for percent_str, expected in self.tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]

    def test_parse_percent_negative[self]:
        negative_tests = [["-" + s, -f] for s, f in self.tests]
        for percent_str, expected in negative_tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]
6
from unittest.case import TestCase

class ParsePercentCase[TestCase]:
    tests = {
        "150%"              : 1.5,
        "100%"              : 1,
        "99%"               : 0.99,
        "99.999%"           : 0.99999,
        "99.5%"             : 0.995,
        "95%"               : 0.95,
        "90%"               : 0.9,
        "50%"               : 0.5,
        "66.666%"           : 0.66666,
        "42%"               : 0.42,
        "20.5%"             : 0.205,
        "20%"               : 0.2,
        "10%"               : 0.1,
        "3.141592653589793%": 0.03141592653589793,
        "1%"                : 0.01,
        "0.1%"              : 0.001,
        "0.01%"             : 0.0001,
        "0%"                : 0,
    }
    tests = sorted[tests.items[], key=lambda x: -x[1]]

    def test_parse_percent[self]:
        for percent_str, expected in self.tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]

    def test_parse_percent_negative[self]:
        negative_tests = [["-" + s, -f] for s, f in self.tests]
        for percent_str, expected in negative_tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]
7, điều đó có nghĩa là sự thay thế sẽ xảy ra trên tất cả các ký tự không phải từ
from unittest.case import TestCase

class ParsePercentCase[TestCase]:
    tests = {
        "150%"              : 1.5,
        "100%"              : 1,
        "99%"               : 0.99,
        "99.999%"           : 0.99999,
        "99.5%"             : 0.995,
        "95%"               : 0.95,
        "90%"               : 0.9,
        "50%"               : 0.5,
        "66.666%"           : 0.66666,
        "42%"               : 0.42,
        "20.5%"             : 0.205,
        "20%"               : 0.2,
        "10%"               : 0.1,
        "3.141592653589793%": 0.03141592653589793,
        "1%"                : 0.01,
        "0.1%"              : 0.001,
        "0.01%"             : 0.0001,
        "0%"                : 0,
    }
    tests = sorted[tests.items[], key=lambda x: -x[1]]

    def test_parse_percent[self]:
        for percent_str, expected in self.tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]

    def test_parse_percent_negative[self]:
        negative_tests = [["-" + s, -f] for s, f in self.tests]
        for percent_str, expected in negative_tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]
8 đến
from unittest.case import TestCase

class ParsePercentCase[TestCase]:
    tests = {
        "150%"              : 1.5,
        "100%"              : 1,
        "99%"               : 0.99,
        "99.999%"           : 0.99999,
        "99.5%"             : 0.995,
        "95%"               : 0.95,
        "90%"               : 0.9,
        "50%"               : 0.5,
        "66.666%"           : 0.66666,
        "42%"               : 0.42,
        "20.5%"             : 0.205,
        "20%"               : 0.2,
        "10%"               : 0.1,
        "3.141592653589793%": 0.03141592653589793,
        "1%"                : 0.01,
        "0.1%"              : 0.001,
        "0.01%"             : 0.0001,
        "0%"                : 0,
    }
    tests = sorted[tests.items[], key=lambda x: -x[1]]

    def test_parse_percent[self]:
        for percent_str, expected in self.tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]

    def test_parse_percent_negative[self]:
        negative_tests = [["-" + s, -f] for s, f in self.tests]
        for percent_str, expected in negative_tests:
            parsed = percent_to_float[percent_str]
            self.assertEqual[expected, parsed, percent_str]
9 và ký tự dấu chấm thập phân. Do đó, mọi nhân vật khác được thay thế bằng một ký tự trống [có nghĩa là nó bị loại bỏ].

Bản tóm tắt

Để chuyển đổi chuỗi phần trăm thành số thập phân, hãy sử dụng chức năng được tích hợp trong chức năng thay thế các phương thức chuỗi như vậy:

>>> float["30.0%"]
Traceback [most recent call last]:
File "", line 1, in
ValueError: could not convert string to f
loat: '30.0%'
0.

Nếu chuỗi tỷ lệ phần trăm chứa các ký tự khác ngăn chặn chuyển đổi, bạn có thể muốn nhập thư viện Regex và sử dụng phương thức

>>> float["30.0%"]
Traceback [most recent call last]:
File "", line 1, in
ValueError: could not convert string to f
loat: '30.0%'
1 như vậy:
>>> float["30.0%"]
Traceback [most recent call last]:
File "", line 1, in
ValueError: could not convert string to f
loat: '30.0%'
2.

Bài Viết Liên Quan

Chủ Đề