圆括号周围的Python间距

时间:2016-11-15 14:16:18

标签: 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'. 

唯一的区别似乎是括号周围的间距。我无法从一开始就将空间移除。

4 个答案:

答案 0 :(得分:4)

更简单的方法是使用.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="")

答案 1 :(得分:1)

如果使用str.format,则可以更好地控制inter参数间距(print使用默认的单个空格):

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

答案 2 :(得分:0)

如果您无法使用Personal执行此操作,请不要将它们作为不同的参数提供(使用format的默认sep。)< / p>

即,将' '转换为percent_with_e并加入str

+

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

format

答案 3 :(得分:0)

这是打印格式的问题。将多个参数传递给print函数时,它会自动插入空格。如果要格式化字符串,最好的方法是使用&#39;%&#39;操作

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