0

I am beginner of python and trying to insert percentage sign in the output. Below is the code that I've got.

print('accuracy :', accuracy_score(y_true, y_pred)*100)

when I run this code I got 50.0001 and I would like to have %sign at the end of the number so I tried to do as below

print('Macro average precision :', precision_score(y_true, y_pred, average='macro')*100"%\n")

I got error say SyntaxError: invalid syntax Can any one help with this?

Thank you!

Jay
  • 9
  • 1
  • 7
  • You can use formatting `'Macro average precision : {:.0%}\n'.format(precision_score(y_true, y_pred, average='macro'))` – Olvin Roght Apr 13 '20 at 07:45
  • The syntax error is because you simply concatenated a float expression with a character string; this is nonsense in Python. Vis. `print(50.001"%\n")`. – Prune Apr 13 '20 at 07:49

4 Answers4

1

Use f strings:

print(f"Macro average precision : {precision_score(y_true, y_pred, average='macro')*100}%\n")

Or convert the value to string, and add (concatenate) the strings:

print('Macro average precision : ' + str(precision_score(y_true, y_pred, average='macro')*100) + "%\n")

See the discussion here of the merits of each; basically the first is more convenient; and the second is computationally faster, and perhaps more simple to understand.

Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
Peter Prescott
  • 768
  • 8
  • 16
0

The simple, "low-tech" way is to correct your (lack of) output expression. Convert the float to a string and concatenate. To make it easy to follow:

pct = precision_score(y_true, y_pred, average='macro')*100
print('Macro average precision : ' + str(pct) + "%\n")

This is inelegant, but easy to follow.

Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
Prune
  • 76,765
  • 14
  • 60
  • 81
0

You can try this:

print('accuracy: {:.2f}%'.format(100*accuracy_score(y_true, y_pred)))
libingallin
  • 131
  • 3
0

One of the ways to go about fixing this is by using string concatenation. You can add the percent symbol to your output from your function using a simple + operator. However, the output of your function needs to be cast to a string data type in order to be able to concatenate it with a string. To cast something to a string, use str()

So the correct way to fix your print statement using this explanation would be:

print('Macro average precision : ' + str(precision_score(y_true, y_pred, average='macro')*100) + "%\n")
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35