lolo
lolo

Reputation: 177

What is the meaning of %()s in Python?

I see like this %(asctime)s in the logging module

What is the meaning of %()s instead of %s?

I only know %s means "string" and I can't find other information about %()s on the internet.

Upvotes: 15

Views: 16681

Answers (2)

Taylr Cawte
Taylr Cawte

Reputation: 612

%(asctime)s is a placeholder used by the logging module to get the 'asctime' attribute of a LogRecord object.

The notation '%(key)s' is used to identify a key within a mapping and insert its value in a format string. For example, consider a person named john who is 168 cm tall and weighs 72 kilos.

person = {'name': 'john', 'height': 168, 'weight': 72}

If you wanted to print their name and weight, you wouldn't need to specify each instance that is inserted nor would you need to account for the fact that the weight is an int. All you need to do is specify the keys you want (within the %()s specifiers) and supply the mapping where those items are stored after the %.

>>> print('%(name)s, %(weight)s' % person)
john, 72

This method of string formatting is similar to str.format():

>>> print('{name}, {weight}'.format(**person))
john, 72

Upvotes: 8

CryptoFool
CryptoFool

Reputation: 23079

This is a string formatting feature when using the % form of Python string formatting to insert values into a string. The case you're looking at allows named values to be taken from a dictionary by providing the dictionary and specifying keys into that dictionary in the format string. Here's an example:

values = {'city': 'San Francisco', 'state': 'California'}
s = "I live in %(city)s, %(state)s" % values
print(s)

Result:

I live in San Francisco, California

Upvotes: 16

Related Questions