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.
'''
Related
The literal 3e4 represents the float 30000 in python (3.8 at least).
>>> print(3e4)
30000.0
The syntax of the following code is clearly invalid:
x=4
3ex
3ex is not a valid expression, but the example helps me ask my question:
Clearly, the expression 3*10**4 represents the same number, but my question here is purely related to the scientific notation literals. Just for my curiosity, is there a way to use the same syntax with a variable power, better than:
x=4
eval(f"1e{x}")
One subtle difference between 3e4 and 3*10**4 is the type (float and int respectively).
Is there also a difference in execution time perhaps in calculating these two expressions?
To your first question: No, the documentation does not suggest you can.
Is there a way to use the same syntax with a variable power?
When float is instantiated from a string, it calls out to a CPython C library PyOS_string_to_double to which handles making the str locale-aware (. vs ,) before passing the string directly to the C function strtod doc.
Meanwhile the documentation for PyOS_string_to_double does not mention of any special way to configure the exponent.
To your second question about performance, this is easily benchmarked. But, we do not have a candidate to benchmark against. So, this is a moot question.
Is there also a difference in execution time perhaps?
I hope this satiates your curiosity. If not, feel free to dig into the C code that I linked.
f-strings don't behave nicely when used with dictionaries, as mentioned here.
Here is an example of the not-so-nice behavior:
d = {'foo': 'bar'}
# Both work as expected
d["foo"]
d['foo']
# This only works when different quotations are used in the inner and outer strings
f'{d["foo"]}'
f"{d['foo']}"
# This doesn't work
f'{d['foo']}'
f"{d["foo"]}"
# The .format() method doesn't care
'{}'.format(d['foo'])
The last two f-strings listed result in a SyntaxError: invalid syntax, which happens because the string '{d['foo']}' is evaluated as '{d['foo']}'.
What is the underlying reason everything inside the curly brackets of f-strings doesn't get evaluated separately, as when using the old .format() method, and what could possibly be the reason for implementing f-strings in this way?
I love f-strings, but this seems like a point in favor of the old method.
F-strings are literal strings. Including unescaped quotes within quotes (of the same type) is invalid syntax. This makes sense, since the result is ambiguous: the interpreter will not know when the string should end. One traditional way of including quotes within quotes is to use a backslash. But PEP498 forbids backslashes in expressions within f-strings:
Backslashes may not appear inside the expression portions of
f-strings...You can use a different type of quote inside the expression...
Therefore, the only way left to access a dictionary value given a key in an f-string expression is to use a different type quote. Using single quotes, or double quotes, everywhere is ambiguous and gives SyntaxError.
str.format is a regular method, and as such works differently: d['foo'] is evaluated before the string is constructed. Just like when you feed arguments to a function, the arguments are evaluated before the function does anything.
This has nothing to do with f-strings. f strings are common strings once evaluated. What you are trying would be a problem with standard strings too
The problem is that
'a "b" c'
is declares the literal a "b" c
while
'a 'b' c'
the quotes close and reopen. So, it is equivalent to string a, followed by variable b, followed by string c.
That's the whole reason python supports both types of quotation marks
According to PEP 498, f-strings rely on the implementation of regular string literals, and as such are subject to the same constraints. In addition to those, f-strings have their own constraints, such as the exclusion of backslashes anywhere within expressions.
A rationale for the choice of implementation has not been published, but ease of implementation, backwards compatibility, syntax highlighting, and consistency with existing interpolation syntax all featured in discussions among core developers on the publicly accessible mailing lists.1
A central point of contention was whether the proposed concept constitutes a string with special properties or a string interjected with code.2 The former view was favored. PEP 536, embodying the dissenting view and additionally seeking to lift several syntactic constraints, was subsequently filed.
Based on this discussion, a tentative compromise of prohibiting backslashes within expressions was agreed upon, leaving string delimiter inversion as the only remaining option for indexing dictionaries within f-string expressions.
Select discussions predating f-string introduction (Python 3.6):
[Python-ideas] Briefer string format
Re: [Python-ideas] Briefer string format
Re: [Python-ideas] Briefer string format
[Python-ideas] String interpolation for all literal strings
[Python-Dev] PEP-498: Literal String Formatting
[Python-Dev] PEP 498 f-string: is it a preprocessor?
[Python-Dev] PEP 498 href="interpolated f-string" tweak
[Python-Dev] Parsing f-strings from PEP 498 -- Literal String Interpolation
[Python-ideas] Let’s make escaping in f-literals impossible
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
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.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Single quotes vs. double quotes in Python
I have seen that when i have to work with string in Python both of the following sintax are accepted:
mystring1 = "here is my string 1"
mystring2 = 'here is my string 2'
Is anyway there any difference?
Is it by any reason better use one solution rather than the other?
Cheers,
No, there isn't. When the string contains a single quote, it's easier to enclose it in double quotes, and vice versa. Other than this, my advice would be to pick a style and stick to it.
Another useful type of string literals are triple-quoted strings that can span multiple lines:
s = """string literal...
...continues on second line...
...and ends here"""
Again, it's up to you whether to use single or double quotes for this.
Lastly, I'd like to mention "raw string literals". These are enclosed in r"..." or r'...' and prevent escape sequences (such as \n) from being parsed as such. Among other things, raw string literals are very handy for specifying regular expressions.
Read more about Python string literals here.
While it's true that there is no difference between one and the other, I encountered a lot of the following behavior in the opensource community:
" for text that is supposed to be read (email, feeback, execption, etc)
' for data text (key dict, function arguments, etc)
triple " for any docstring or text that includes " and '
No. A matter of style only. Just be consistent.
I tend to using " simply because that's what most other programming languages use.
So, habit, really.
There's no difference.
What's better is arguable. I use "..." for text strings and '...' for characters, because that's consistent with other languages and may save you some keypresses when porting to/from different language. For regexps and SQL queries, I always use r'''...''', because they frequently end up containing backslashes and both types of quotes.
Python is all about the least amount of code to get the most effect. The shorter the better. And ' is, in a way, one dot shorter than " which is why I prefer it. :)
As everyone's pointed out, they're functionally identical. However, PEP 257 (Docstring Conventions) suggests always using """ around docstrings just for the purposes of consistency. No one's likely to yell at you or think poorly of you if you don't, but there it is.