ThunderBear
ThunderBear

Reputation: 3

Python spacing around parentheses

Im trying to remove the parenthesis around what is being printed.

Here is my print function

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

It prints like this

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

But I need it to print like this

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

The only difference seems to be the spacing around the parentheses. I cant get the space to be removed from the beginning.

Upvotes: 0

Views: 1460

Answers (4)

zondo
zondo

Reputation: 20336

An easier way would be to use a format string:

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

Which is a newer way to accomplish the old format method:

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

If you want to continue with the commas, you'll need the sep keyword argument:

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

Upvotes: 5

Javier Paz Sedano
Javier Paz Sedano

Reputation: 145

That's an issue with the print formatting. When passing multiple arguments to the print function, it automatically inserts spaces. If you want to format the string, the best way is to use the '%' operator.

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

Upvotes: 0

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160397

If you can't do it with format just don't supply them as different arguments (for which the default sep of ' ' is used).

That is, transform the percent_with_e to a str and join with +:

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

Or, with 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'

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78546

You can better control the inter parameter spacing (print uses a default single space) if you use str.format:

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

Upvotes: 1

Related Questions