Search code examples
pythonstring-formattingstring-interpolation

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.


Solution

  • 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