This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String formatting options: pros and cons
What's the difference between
"%.2f" % x
and
"{:.2f}".format(x)
I am a bit confused about which method should I use and for which version of Python.
In general you want to use the 2nd form (.format()) it's newer and the other one will eventually go away (at least that was the intention at some point - see Notes below).
To quote the Python What’s New In Python 3.0 docs:
A new system for built-in string formatting operations replaces the %
string formatting operator. (However, the % operator is still
supported; it will be deprecated in Python 3.1 and removed from the
language at some later time.) Read PEP 3101 for the full scoop.
.format() has been available since at least Python 2.6
More information about Advanced String Formatting (PEP 3101)
Notes:
#Duncan also mentions a reference to a thread that discusses whether/when the % based formatting will go away in the comments below. And #NedBatchelder has this definite quote from the Python 3.2 docs: "... there are no current plans to deprecate printf-style formatting."
%-style tends to be briefer, but also more limited. .format() has some advantages:
allows user-defined classes to provide their own formatting flags,
can access attributes of objects
though in your example with floats, neither of those is an advantage.
Both of these techniques will continue to work, so which you use is up to you. There had been an idea that %-formatting would be removed from Python 3, but that is no longer true. See the 3.2 docs:
As the new String Formatting syntax is more flexible and handles tuples and dictionaries naturally, it is recommended for new code. However, there are no current plans to deprecate printf-style formatting.
Related
This question already has answers here:
f-strings vs str.format()
(5 answers)
Closed 2 years ago.
These two print statements produce the same results and at least to me the first version looks more readable.
Should I stick with the f' version because it will cause issues for me later on or cause worse performance or does not follow the present Python standards? Or is it only a question of consistent usage of one of these versions?
print('My first bicycle was a ' + bicycles[1])
print(f'My first bicycle was a {bicycles[1]})')
From PEP 498, a PEP (Python Enhancement Proposals) dedicated to Literal String Interpolation,
F-strings provide a way to embed expressions inside string literals,
using a minimal syntax. It should be noted that an f-string is really
an expression evaluated at run time, not a constant value. In Python
source code, an f-string is a literal string, prefixed with ‘f’, which
contains expressions inside braces. The expressions are replaced with
their values.
The main point here is the highlighted text. That means it is way better in evaluation due to the internal implementation of ASTs (abstract syntax trees) by the CPython compiler which makes them fast.
Also, I think it is more readable and in case of more variables in your string it provides better readability. Multi-line string interpolation can be performed easily using this syntax.
For example,
f'''
My first bicycle was a {bicycles[0]}
It has color {bicycles[0]["color"]}
and has {bicycles[0]["gears"]} gears.
'''
I hope I am making sense with this question.
Sometimes if I print a small float it'll look like 6.1248979238e-05 or something similar.
I want to be able to say "No matter what, output 10 digits precision like so": 0.abcdefghij
>>> '%0.10f'% 6.1248979238e-05
'0.0000612490'
This is "string interpolation" or printf-style formatting which is still widely supported and used. Another option is the newer style string formatting:
>>> '{:.10f}'.format(6.1248979238e-05)
'0.0000612490'
Or if you want to be python2.6 compatible:
>>> '{0:.10f}'.format(6.1248979238e-05)
'0.0000612490'
Take your pick. Which version you use depends on which versions of python you want to support. If you're targeting only python2.7, it doesn't matter. If you want to support earlier versions use printf-style. I've personally switched to using the last form in most of my code. I don't care about python2.5 support, but python2.6 is still new enough that I'd like to support it where possible.
This question already has answers here:
String formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 7 years ago.
In Python there seem to be two different ways of generating formatted output:
user = "Alex"
number = 38746
print("%s asked %d questions on stackoverflow.com" % (user, number))
print("{0} asked {1} questions on stackoverflow.com".format(user, number))
Is there one way to be preferred over the other? Are they equivalent, what is the difference? What form should be used, especially for Python3?
Use the format method, especially if you're concerned about Python 3 and the future. From the documentation:
The formatting operations described here are modelled on C's printf()
syntax. They only support formatting of certain builtin types. The
use of a binary operator means that care may be needed in order to
format tuples and dictionaries correctly. As the new
:ref:string-formatting syntax is more flexible and handles tuples and
dictionaries naturally, it is recommended for new code. However, there
are no current plans to deprecate printf-style formatting.
.format was introduced in Python2.6
If you need backward compatibility with earlier Python, you should use %
For Python3 and newer you should use .format for sure
.format is more powerful than %. Porting % to .format is easy but the other way round can be non trivial
The docs say that the format method is preferred for new code. There are currently no plans to remove % formatting, though.
You can use both .No one said % formatting expression is deprecated.However,as stated before the format method call is a tad more powerful.
Also note that the % expressions are bit more concise and easier to code.Try them and see what suits you best
I'm trying to write a Python C extension that processes byte strings, and I have something basically working for Python 2.x and Python 3.x.
For the Python 2.x code, near the start of my function, I currently have a line:
if (!PyArg_ParseTuple(args, "s#:in_bytes", &src_ptr, &src_len))
...
I notice that the s# format specifier accepts both Unicode strings and byte strings. I really just want it to accept byte strings and reject Unicode. For Python 2.x, this might be "good enough"--the standard hashlib seems to do the same, accepting Unicode as well as byte strings. However, Python 3.x is meant to clean up the Unicode/byte string mess and not let the two be interchangeable.
So, I'm surprised to find that in Python 3.x, the s format specifiers for PyArg_ParseTuple() still seem to accept Unicode and provide a "default encoded string version" of the Unicode. This seems to go against the principles of Python 3.x, making the s format specifiers unusable in practice. Is my analysis correct, or am I missing something?
Looking at the implementation for hashlib for Python 3.x (e.g. see md5module.c, function MD5_update() and its use of GET_BUFFER_VIEW_OR_ERROUT() macro) I see that it avoids the s format specifiers, and just takes a generic object (O specifier) and then does various explicit type checks using the GET_BUFFER_VIEW_OR_ERROUT() macro. Is this what we have to do?
I agree with you -- it's one of several spots where the C API migration of Python 3 was clearly not designed as carefully and thouroughly as the Python coder-visible parts. I do also agree that probably the best workaround for now is focusing on "buffer views", per that macro -- until and unless something better gets designed into a future Python C API (don't hold your breath waiting for that to happen, though;-).
String formatting expressions:
'This is %d %s example!' % (1, 'nice')
String formatting method calls:
'This is {0} {1} example!'.format(1, 'nice')
I personally prefer the method calls (second example) for readability but since it is new, there is some chance that one or the other of these may become deprecated over time. Which do you think is less likely to be deprecated?
Neither; the first one is used in a lot of places and the second one was just introduced. So the question is more which style you prefer. I actually prefer the dict based formatting:
d = { 'count': 1, 'txt': 'nice' }
'This is %(count)d %(txt)s example!' % d
It makes sure that the right parameter goes into the right place, allows to reuse the same parameter in several places, etc.
I thought I read that the % operator is being deprecated in 3.1 already, so I'd stick with the format() function.
See PEP 3101: A New Approach To String Formatting
The original idea was to gradually switch to str.format() approach while allowing both ways:
PEP 3101:
The new system does not collide with any of the method names of the existing string formatting techniques, so both systems can co-exist until it comes time to deprecate the older system.
The idea is still being pursued:
We are still encouraging people to use the new str.format().
Python Issue 7343
Since the original '%' approach is planned to be deprecated and removed at some point in the future, I would suggest writing new code with str.format(). Though at the moment, it is just a matter of personal preference. I personally prefer using dictionary-based formatting, which is supported by both '%' operator and str.format() method.