圆括号内的Python间距
问题描述:
我试图去除正在打印的括号。圆括号内的Python间距
这里是我的打印功能
print("The text contains", totalChars, "alphabetic characters of which", numberOfe, "(", percent_with_e, "%)", "are 'e'.")
它打印出这样的
The text contains 5 alphabetic characters of which 5 (100.0 %) are 'e'.
但我需要它来打印这样
The text contains 5 alphabetic characters, of which 5 (100.0%) are 'e'.
唯一的区别似乎是间距围绕括号。我无法获得从一开始就被删除的空间。
答
您可以更好地控制参数间的间距(打印使用默认的空单)如果你使用str.format
:
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
:
s = "The text contains {} alphabetic characters of which {} ({}) are 'e'".format(totalChars, numberOfe, percent_with_e)
print(s)
The text contains 5 alphabetic characters of which 5 (100.0) are 'e'
答
一个更简单的方法是将格式化为.format()
方法的字符串:
print("The text contains {} alphabetic characters, of which {} ({}%) are 'e'".format(totalChars, numberOfe, percent_with_e))
如果您想继续使用逗号,你需要的sep
关键字参数:
print("The text contains ", totalChars, " alphabetic characters of which ", numberOfe, " (", percent_with_e, "%) ", "are 'e'.", sep="")
答
这是与打印格式的问题。将多个参数传递给打印函数时,会自动插入空格。如果要格式化字符串,最好的方法是使用'%'运算符。
percent = "(%d%%)" % percent_with_e
print("The text contains", totalChars, "alphabetic characters of which", numberOfe, percent, "are 'e'.")
这听起来像你需要字符串格式。 –