String with 'F' Prefix in Python-3.6

String with 'f' prefix in python-3.6

See PEP 498 Literal String Interpolation:

The expressions that are extracted from the string are evaluated in the context where the f-string appeared. This means the expression has full access to local and global variables. Any valid Python expression can be used, including function and method calls.

So the expressions are evaluated as if they appear in the same scope; locals, closures, and globals all work the same as in other code in the same context.

You'll find more details in the reference documentation:

Expressions in formatted string literals are treated like regular Python expressions surrounded by parentheses, with a few exceptions. An empty expression is not allowed, and a lambda expression must be surrounded by explicit parentheses. Replacement expressions can contain line breaks (e.g. in triple-quoted strings), but they cannot contain comments. Each expression is evaluated in the context where the formatted string literal appears, in order from left to right.

Since you are trying out a 3.6 alpha build, please do read the What's New In Python 3.6 documentation. It summarises all changes, including links to the relevant documentation and PEPs.

And just to be clear: 3.6 isn't released yet; the first alpha is not expected to be released until May 2016. See the 3.6 release schedule.

What are formatted string literals in Python 3.6?

Simple is better than complex.

So here we have formatted string. It gives the simplicity to the string formatting, while keeping the code explicit (comprared to other string formatting mechanisms).

title = 'Mr.'
name = 'Tom'
count = 3

# This is explicit but complex
print('Hello {title} {name}! You have {count} messages.'.format(title=title, name=name, count=count))

# This is simple but implicit
print('Hello %s %s! You have %d messages.' % (title, name, count))

# This is both explicit and simple. PERFECT!
print(f'Hello {title} {name}! You have {count} messages.')

It is designed to replace str.format for simple string formatting.

What is print(f...)

The f means Formatted string literals and it's new in Python 3.6.



A formatted string literal or f-string is a string literal that is
prefixed with f or F. These strings may contain replacement
fields, which are expressions delimited by curly braces {}. While
other string literals always have a constant value, formatted strings
are really expressions evaluated at run time.


Some examples of formatted string literals:

>>> name = "Fred"
>>> f"He said his name is {name}."
"He said his name is Fred."

>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is Fred."

>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
"He said his name is Fred."

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
result: 12.35

>>> today = datetime(year=2017, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
January 27, 2017

>>> number = 1024
>>> f"{number:#0x}" # using integer format specifier
0x400

I know of f-strings, but what are r-strings? Are there others?

  1. An r-string is a raw string.
  • It ignores escape characters. For example, "\n" is a string containing a newline character, and r"\n" is a string containing a backslash and the letter n.
  • If you wanted to compare it to an f-string, you could think of f-strings as being "batteries-included." They have tons of flexibility in the ability to escape characters and execute nearly arbitrary expressions. The r-string on the other hand is stripped down and minimalist, containing precisely the characters between its quotation marks.
  • As far as actually using the things, typically you would use an r-string if you're passing the string into something else that uses a bunch of weird characters or does its own escaping so that you don't have to think too hard about how many backslashes you really need to get everything to work correctly. In your example, they at least needed r-strings to get the \a bit working correctly without double escapes. Note that '$\\alpha > \\beta$' is identical to r'$\alpha > \beta$'.

  1. Since you're using f-strings, I'll assume you have at least Python 3.6. Not all of these options are supported for older versions but any of the following prefixes are valid in Python 3.6+ in any combination of caps and lowers: r, u, f, rf, fr, b, rb, br
  • The b-strings are binary literals. In Python 2 they do nothing and only exist so that the source code is compatible with Python 3. In Python 3, they allow you to create a bytes object. Strings can be thought of as a view of the underlying bytes, often restricted as to which combinations are allowed. The distinction in types helps to prevent errors from blindly applying text techniques to raw data. In Python 3, note that 'A'==b'A' is False. These are not the same thing.
  • The u-strings are unicode literals. Strings are unicode by default in Python 3, but the u prefix is allowed for backward compatibility with Python 2. In Python 2, strings are ASCII by default, and the u prefix allows you to include non-ASCII characters in your strings. For example, note the accented character in the French phrase u"Fichier non trouvé".
  • In the kind of code I write, I rarely need anything beyond r, u, f, and b. Even b is a bit out there. Other people deal with those prefixes every day (presumably). They aren't necessarily anything you need to familiarize yourself with, but knowing they exist and being able to find their documentation is probably a good skill to have.

Just so that it's in an answer instead of buried in a comment, Peter Gibson linked the language specification, and that's the same place I pulled the prefix list from. With your math background, a formal language specification might be especially interesting — depending a little on how much you like algebra and mathematical logic.

Even if it's just for a semantically trivial language like Forth, I think many programmers would enjoy writing a short interpreter and gain valuable insight into how their language of choice works.

Can I import Python's 3.6's formatted string literals (f-strings) into older 3.x, 2.x Python?

Unfortunatly if you want to use it you must require Python 3.6+, same with the matrix multiplication operator @ and Python 3.5+ or yield from (Python 3.4+ I think)

These made changes to how the code is interpreted and thus throw SyntaxErrors when imported in older versions. That means you need to put them somewhere where these aren't imported in older Pythons or guarded by an eval or exec (I wouldn't recommend the latter two!).

So yes, you are right, if you want to support multiple python versions you can't use them easily.

Expressions with Python 3.6 'f' strings not compatible with `.format` or `.format_map`

You are looking for eval

>>> def format_map_eval(string, mapping):
... return eval(f'f{string!r}', mapping)
...
>>> version = '1.13.8.10'
>>> some_config_string = 'example-{".".join(version.split(".")[:3])}'
>>> format_map_eval(some_config_string, dict(version=version))
'example-1.13.8'

This at least is explicit about you providing this.

The key feature of f-strings is that they evaluate arbitrary expressions inside their formatting brackets. If you want a function call that does this, you are asking for eval.

Now that I think about it, I'm not sure this is safe or portable across implementations because there is no guarantee about the repr of str as far as I know.

Formatted string literals in Python 3.6 with tuples

Your first str.format() call is a regular method call with 3 arguments, there is no tuple involved there. Your second call uses the * splat call syntax; the str.format() call receives 3 separate individual arguments, it doesn't care that those came from a tuple.

Formatting strings with f don't use a method call, so you can't use either technique. Each slot in a f'..' formatting string is instead executed as a regular Python expression.

You'll have to extract your values from the tuple directly:

f'{t[0]}, {t[1]}, {t[2]}'

or first expand your tuple into new local variables:

a, b, c = t
f'{a}, {b}, {c}'

or simply continue to use str.format(). You don't have to use an f'..' formatting string, this is a new, additional feature to the language, not a replacement for str.format().

From PEP 498 -- Literal String Interpolation:

This PEP does not propose to remove or deprecate any of the existing string formatting mechanisms.

Different prefixes in regex.compile() argument in python

A formatted string literal or f-string is a string literal that is prefixed with 'f' or 'F'.

These strings may contain replacement fields, which are expressions delimited by curly braces {}.

While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.

IN THIS CASE:

The curly brackets around the 'string.punctuation`` are a replacement field, i.e. the string is to be formatted withstring.punctuation, which, in Python, is a 'string of ASCII characters which are considered punctuation marks in theC` locale'.

To find out more, check out these Python docs and string.punctuation references :-)

F string prefix in python giving a syntax error

F-strings were a new feature introduced in Python 3.6, so of course they're not going to work in 3.5.2.

Python and F-Strings explanation

No, 'snow' is a string literal, an expression that produces a string value. snow would be a variable name (note the lack of quotes).

Compare:

>>> 'snow'
'snow'
>>> snow
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'snow' is not defined
>>> snow = 42
>>> snow
42
>>> snow = 'snow'
>>> snow
'snow'

The variable snow at first wasn't yet assigned to, so trying to use it caused an exception. I then assigned an integer to the name, and then the string with value 'snow'.

Formatting a string literal with another string literal is pretty meaningless. You'd normally use an actual variable, so you can vary the output produced:

compared_to = 'snow'
print("It's fleece was white as {}.".format(compared_to))

Also, that's not an f string. An f string literal starts with a f character. What you have here is a regular, run-of-the-mill string literal, and a call to the str.format() method. The following is the equivalent expression using an f-string:

print(f"It's fleece was white as {'snow'}.")

See String with 'f' prefix in python-3.6 for more information on actual f-strings.



Related Topics



Leave a reply



Submit