圆括号周围的Python间距

2024-05-14 13:41:25 发布

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

我正试图去掉打印内容周围的括号。在

这是我的打印功能

print("The text contains", totalChars, "alphabetic characters of which", numberOfe, "(", percent_with_e, "%)", "are 'e'.")

像这样印出来的

^{pr2}$

但我需要这样打印

The text contains 5 alphabetic characters, of which 5 (100.0%) are 'e'. 

唯一的区别似乎是括号周围的间距。我不能从一开始就把空间移走。在


Tags: ofthetext功能内容whichare括号
3条回答

更简单的方法是使用.format()方法格式化字符串:

print("The text contains {} alphabetic characters, of which {} ({}%) are 'e'".format(totalChars, numberOfe, percent_with_e))

如果要继续使用逗号,则需要sep关键字参数:

^{pr2}$

如果使用^{},可以更好地控制参数间的间距(print使用默认的单个空格):

print("The text contains {} alphabetic characters\
       of which {} ({}%) are 'e'.".format(totalChars, numberOfe, percent_with_e))

如果你不能用format来做,那就不要把它们作为不同的参数来提供(默认使用' 'sep)。在

也就是说,将percent_with_e转换为str,并用+连接:

print("The text contains", totalChars, "alphabetic characters of which", numberOfe, "(" + str(percent_with_e) + "%)", "are 'e'.")

或者,使用format

^{pr2}$

相关问题 更多 >

    热门问题