Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string format: When to use !s conversion flag

Tags:

What's the difference between these 2 string format statements in Python:

'{0}'.format(a) '{0!s}'.format(a) 

Both have the same output if a is an integer, list or dictionary. Is the first one {0} doing an implicit str() call?

Source

PS: keywords: exclamation / bang "!s" formatting

like image 758
click Avatar asked Aug 22 '14 07:08

click


People also ask

What does S mean in a Python format string?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string.

What does %S and %D do in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

Is string formatting important in Python?

Python string class gives us an important built-in command called format() that helps us to replace, substitute, or convert the string with placeholders with valid values in the final string.

What does __ format __ do in Python?

The __format__ method is responsible for interpreting the format specifier, formatting the value, and returning the resulting string. It is safe to call this function with a value of “None” (because the “None” value in Python is an object and can have methods.)


1 Answers

It is mentioned in the documentation:

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.

Two conversion flags are currently supported: '!s' which calls str() on the value, and '!r' which calls repr().

An example can be taken (again from the documentation) to show the difference:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2" 
like image 83
hjpotter92 Avatar answered Sep 23 '22 02:09

hjpotter92