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!

2
  • You can use formatting 'Macro average precision : {:.0%}\n'.format(precision_score(y_true, y_pred, average='macro')) Commented Apr 13, 2020 at 7: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"). Commented Apr 13, 2020 at 7:49

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can try this:

print('accuracy: {:.2f}%'.format(100*accuracy_score(y_true, y_pred)))

Comments

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.

Comments

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.