社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

L. B.

L. B. 最近创建的主题
L. B. 最近回复了
5 年前
回复了 L. B. 创建的主题 » python中如何在负数前加括号

如果你想让它更具可读性,这是另一种选择:

def beauty(coeff, i):

    if(coeff == 0): return ''

    if(i == 2):

        if(coeff ==  1): return  "x\u00B2"
        if(coeff == -1): return "-x\u00B2"
        return f"{coeff}x\u00B2"

    if(i == 1):

        if(coeff ==  1): return "+x"
        if(coeff == -1): return "-x"
        if(coeff  >  0): return f"+{coeff}x"
        return f"{coeff}x"

    if(i == 0):

        if(coeff >  0): return f"+{coeff}"
        return f"{coeff}"


def PrintQuadratic():

    a = int(input('a: '))
    b = int(input('b: '))
    c = int(input('c: '))

    print(f"{beauty(a,2)}{beauty(b,1)}{beauty(c,0)}")

PrintQuadratic()
a: 7
b: 9
c: 13
→ 7x²+9x+13

PrintQuadratic()
a: -1
b:  1
c:  0
→ -x²+x

PrintQuadratic()
a: 4
b: -2
c: 1
→ 4x²-2x+1

它有点长,但能产生很好的指纹。