You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python拆分公式的项?支持多公式通用(附示例)

Hey there, let's figure out how to split algebraic formula terms in Python exactly like you need—turning something like "3x+7-2x" into ["3x", "+7", "-2x"], and making it work reliably for all kinds of formulas. Here's a solid approach:

The Core Idea

We need to split the formula at every position where a new term starts (marked by a + or -), but we want to keep those signs attached to their respective terms. Regular expressions are perfect for this because they let us target those split points without consuming the signs themselves.

Code Implementation

Here's a function that handles all edge cases, including formulas starting with a negative sign:

import re

def split_formula_terms(formula):
    # Handle formulas that start with a negative sign
    if formula.startswith('-'):
        # Split at every position followed by + or -
        terms = re.split(r'(?=[+-])', formula)
    else:
        # Add a leading '+' to make splitting consistent, then strip it from the first term
        prefixed_formula = '+' + formula
        terms = re.split(r'(?=[+-])', prefixed_formula)
        # Remove the artificial leading '+' from the first term
        terms[0] = terms[0][1:]
    
    # Filter out any empty strings that might pop up from edge cases
    return [term for term in terms if term]

Test It Out

Let's run this function against different formula types to make sure it works:

# Basic case from your example
print(split_formula_terms("3x+7-2x"))  # Output: ['3x', '+7', '-2x']

# Formula starting with a negative term
print(split_formula_terms("-3x+5y-8"))  # Output: ['-3x', '+5y', '-8']

# Formula with exponents
print(split_formula_terms("x^2-4x+4"))  # Output: ['x^2', '-4x', '+4']

# Formula with decimals and fractions
print(split_formula_terms("10-2.5x+3/2y"))  # Output: ['10', '-2.5x', '+3/2y']

How It Works

  • The regex (?=[+-]) is a positive lookahead—it finds every position in the string that's immediately followed by + or -, then splits the string at those positions. This keeps the sign attached to the term that comes after it.
  • For formulas that don't start with a sign (like your example), we add a temporary leading + so the splitting logic treats the first term the same way as others. We then remove that extra + from the first term to match your desired output.
  • The final list comprehension filters out any empty strings, which could happen if the formula has leading/trailing signs or unexpected whitespace (you could add a .strip() to the input if whitespace is a concern!).

内容的提问来源于stack exchange,提问作者ole den hertog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:42:04