简体   繁体   中英

ValueError: unsupported format character ')' (0x29) at index 21

I got the code from Automate The Boring Stuff With Python .

import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s(levelname)s- %(message)s')
logging.debug('Start of program')

def factorial(n):
    logging.debug('Start of factorial( %)' % (n))
    total = 1
    for i in range(n + 1):
        total *= i
        logging.debug('i is ' + str(i) + ', total is ' + str(total))
    logging.debug('End of factorial( %)' % (n))
    return total

print (factorial(5))
logging.debug('End of program')

When I run the code, the following error occurs:

2015-06-18 12:51:47,073 - DEBUG- Start of program Traceback (most recent call last): File "/home/raqeeb.alam/PycharmProjects/E_mail/sub_links.py", line 14, in print factorial(5) File "/home/raqeeb.alam/PycharmProjects/E_mail/sub_links.py", line 6, in factorial logging.debug('Start of factorial( %)' % (n)) ValueError: unsupported format character ')' (0x29) at index 21

For these lines:

print (factorial(5))
logging.debug('End of program')

Should be:

logging.debug('Start of factorial(%s)' % (n))
...
logging.debug('End of factorial(%s)' % (n))

BTW: parentheses are redundant here. Could be simply:

logging.debug('Start of factorial(%s)' % n)
...
logging.debug('End of factorial(%s)' % n)

And ' %(asctime)s(levelname)s- %(message)s' should be ' %(asctime)s%(levelname)s- %(message)s'

You're missing a % sign:

logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s%(levelname)s- %(message)s')
#                                                            ^ HERE
logging.debug('Start of factorial( %)' % (n))
logging.debug('End of factorial( %)' % (n))

Those two lines should be

logging.debug('Start of factorial(%s)' % (n))
logging.debug('End of factorial(%s)' % (n))

This is a generally unsupported error. Try this:

It looks like Python is interpreting the % as a printf-like format character. Try using %%

means:

 logging.debug('Start of factorial( %%)' % (n))

.

.

.

 logging.debug('End of factorial( %%)' % (n))

To have more clean code try to remove () around n.

means:

 logging.debug('Start of factorial( %%)' % n)

.

.

.

 logging.debug('End of factorial( %%)' % n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM