What does %s mean in a Python format string?
It is a string formatting syntax (which it borrows from C).
Please see "PyFormat":
Python supports formatting values into
strings. Although this can include
very complicated expressions, the most
basic usage is to insert values into a
string with the%s
placeholder.
Here is a really simple example:
#Python 2
name = raw_input("who are you? ")
print "hello %s" % (name,)
#Python 3+
name = input("who are you? ")
print("hello %s" % (name,))
The %s
token allows me to insert (and potentially format) a string. Notice that the %s
token is replaced by whatever I pass to the string after the %
symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.
What does the `s` in `%s` mean in string formatting?
The d
in %d
stands for decimal. %d
is for formatting numbers. %s
is for formatting strings. (thus, the example you gave actually doesn't work) Yes, it matters. You need to tell Python where to place the thing after the %
operator into the string.
What is the meaning of %()s in Python?
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
Using !s vs. :s to format a string in Python
!s
, and its brethren !a
and !r
apply str()
, ascii()
and repr()
respectively before interpolation and formatting. These are called conversion flags, and are part of the Format String Syntax spec, not the per-field formatting spec applied to values when interpolating:
The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the
__format__()
method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling__format__()
, the normal formatting logic is bypassed.
Bold emphasis mine.
:s
only applies afterwards to the conversion result (or the original object if no conversion had been applied), and only if the __format__
method for the type of object supports that formatting option. Usually, only objects of type str
support this formatter; it's there as the default, mostly because the Format Specification Mini-Language allows for the existence of a type character and because the older %
printf
-style formatting had a %s
format. If you tried to apply the s
type to an object that doesn't support it, you'd get an exception.
Use !s
(or !a
or !r
) when you have an object that is not itself a string and either doesn't support formatting otherwise (not all types do) or would format differently from their str()
, ascii()
or repr()
conversions:
>>> class Foo:
... def __str__(self):
... return "Foo as a string"
... def __repr__(self):
... return "<Foo as repr, with åéæ some non-ASCII>"
... def __format__(self, spec):
... return "Foo formatted to {!r} spec".format(spec)
...
>>> print("""\
... Different conversions applied:
... !s: {0!s:>60s}
... !r: {0!r:>60s}
... !a: {0!a:>60s}
... No conversions: {0:>50s}
... """.format(Foo()))
Different conversions applied:
!s: Foo as a string
!r: <Foo as repr, with åéæ some non-ASCII>
!a: <Foo as repr, with \xe5\xe9\xe6 some non-ASCII>
No conversions: Foo formatted to '>50s' spec
Note: all formatting specified by the format spec are the responsibility of the __format__
method; the last line does not apply the alignment operation in the >50s
formatting spec, the Foo.__format__
method only used it as literal text in a formatting operation (using a !r
conversion here).
For the converted values, on the other hand, the str.__format__
method is used and the output is aligned to the right in a 50 character wide field, padded with spaces on the left.
what means % s.something()%__name__ in Python
It is an "older" form of formatting things into strings. The preferred way (python 3 up) is
print('some{:d}'.format(22)) # with format appended and placeholder
or
print ( f'some{22:d}' ) # inline formatting
will format the number 22 into the string as decimal. Yours is similar, but in your example it will format the content of __name__
into your string, __name__
is set by your class/module - resulting in a string of <classname>.listSelected()
.
See : https://docs.python.org/2/library/string.html#format-specification-mini-language
print('some{:d}'.format(22))
print('Hello %s' % "World") # similar to yours - using python 3, python 2: use no ()
Output:
some22
Hello World
For more information, see Python string formatting: % vs. .format
Python- %s %f %d % etc
This is the Exercise:
As it says, %s (of string) is to replace a string, %f (of float) is to replace a float, and %d (of integer) is to replace an integer
# change this code
mystring = "hello"
myfloat = 10.0
myint = 20
# testing code
if mystring == "hello":
print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
print("Integer: %d" % myint)
Python the Hard Way - exercise 6 - %r versus %s
They are called string formatting operations.
The difference between %s and %r is that %s uses the str
function and %r uses the repr
function. You can read about the differences between str
and repr
in this answer, but for built-in types, the biggest difference in practice is that repr
for strings includes quotes and all special characters are escaped.
Related Topics
"Fire and Forget" Python Async/Await
How to Display Pandas Dataframe of Floats Using a Format String for Columns
Generate 'N' Unique Random Numbers Within a Range
Scope of Lambda Functions and Their Parameters
Python3 --Version Shows "Nameerror: Name 'Python3' Is Not Defined"
How to Upgrade All Python Packages with Pip
How to Install Python3 Version of Package via Pip on Ubuntu
How to Calculate the Date Six Months from the Current Date Using the Datetime Python Module
How to Use Python to Login to a Webpage and Retrieve Cookies for Later Usage
Convert a Number Range to Another Range, Maintaining Ratio
Using Pip Behind a Proxy with Cntlm
How to Generate Keyboard Events
How to Remove a Substring from the End of a String
Python 3 Importerror: No Module Named 'Configparser'
Splitting a List into N Parts of Approximately Equal Length