random student
random student

Reputation: 775

printing special character % in python without extra ' ' around it

I'm trying to print like this

per = repr('%')
print('Accuracy score is %s%s'%(round(accuracy*100,2),per))

which i hope to display Accuracy score is 78.13% it returns Accuracy score is 78.13'%'. I don't want that awkward ' ' sticking around my %. How could i remove that ' '? or is there any way to print it?

Upvotes: 0

Views: 113

Answers (5)

Voiceroy
Voiceroy

Reputation: 330

You just have to use r'%' in place of per in

print('Accuracy score is %s%s'%(round(accuracy*100,2),r'%'))

Upvotes: 0

user7548672
user7548672

Reputation:

f-strings are string literals which provide a readable way to include the value of Python expressions inside strings.

f'Accuracy score is {round(accuracy*100,2)}'

Upvotes: 1

Sam
Sam

Reputation: 1415

By using repr('%') you are adding the extra quotation marks:

>>> per1 = '%'
>>> per2 = repr('%')
>>> per1
'%'
>>> per2
"'%'"

But honestly, an easier way would be to just put an escaped % literal in your print statement. For the % you would escape it with another %, e.g.:

print('Accuracy score is %s%% '%(round(accuracy*100,2)))
Accuracy score is 78.13%

Upvotes: 1

yoskovia
yoskovia

Reputation: 360

You could use .format instead

print('Accuracy score is {}%'.format(round(accuracy*100,2)))

Output:

Accuracy score is 97.8%

Upvotes: -1

Michael Waddell
Michael Waddell

Reputation: 289

You can include a literal % with a double %% like so:

print('Accuracy score is %s%%' % round(accuracy*100,2))

Upvotes: 2

Related Questions