F字符串未打印

2024-09-30 00:34:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将结果打印到终端,但f-string似乎不起作用,如下所示:

print(
    f'Financial Analysis\n'
    '----------------------\n'  
    'Total Months {monthnum}\n' 
    'Total: ${pl}\n'
    'Greatest increase in profits: {greatim} ({greati}) \n'
    'Greatest decrease in profits: {greatdm} ({greatd})'
    )

代码的其余部分在this repository上可用


Tags: in终端stringanalysistotalplprintfinancial
2条回答

我认为您需要在引用变量的行中使用f'',如下所示:

print(
    'Financial Analysis\n'
    '           \n'  
    f'Total Months {monthnum}\n' 
    f'Total: ${pl}\n'
    f'Greatest increase in profits: {greatim} ({greati}) \n'
    f'Greatest decrease in profits: {greatdm} ({greatd})'
    )

在您的例子中,我还认为在字符串末尾使用.format()方法可能更干净,但这是个人的选择

在代码中,只有第一个字符串是f字符串。如果你想插值,你需要把它们都变成f字符串

或者,您可以使用带有多行引号的f字符串(即''' ''')。这可能是一个更好的解决方案:

monthnum = 10
pl = "some pl"
greatim = "gim"
greati = 'gti'
greatdm = 'gdm'
greatd = 'gd'

print(f'''Financial Analysis
           
Total Months {monthnum} 
Total: ${pl}
Greatest increase in profits: {greatim} ({greati})
Greatest decrease in profits: {greatdm} ({greatd})'''
)

印刷品:

Financial Analysis
           
Total Months 10 
Total: $some pl
Greatest increase in profits: gim (gti)
Greatest decrease in profits: gdm (gd)

相关问题 更多 >

    热门问题