[HN Gopher] Python 3's F-Strings: An Improved String Formatting ...
       ___________________________________________________________________
        
       Python 3's F-Strings: An Improved String Formatting Syntax
        
       Author : mmastrac
       Score  : 54 points
       Date   : 2021-01-19 16:39 UTC (1 days ago)
        
 (HTM) web link (realpython.com)
 (TXT) w3m dump (realpython.com)
        
       | timeoperator wrote:
       | PHP: Am I joke to you?
        
         | noncoml wrote:
         | > PHP: Am I joke to you?
         | 
         | JFYI meme style responses are frowned upon at HN. That's why
         | you get downvoted.
         | 
         | A much better rephrase of the above would be something along
         | the lines of:
         | 
         | PHP/Javascript/.. also have this feature since ver X. It's main
         | difference/advantage/disadvantage is ...
        
       | brian_herman wrote:
       | Here is a more in-depth tutorial.
       | https://zetcode.com/python/fstring/
        
       | eachro wrote:
       | This is super minor but I really wish f-string formatting were
       | the default behavior for `print` or that there were a `printf`
       | command just for it. Typing that extra f character before the
       | quotes is just annoying enough
        
         | musicale wrote:
         | And while they're at it, bring back the print statement.
         | 
         | It was a beautiful thing and made it possible to write the same
         | "hello world" program in Python and BASIC:
         | print "hello, world"
        
         | pansa2 wrote:
         | Making f-strings the default was discussed at the Python
         | Language Summit last year:
         | 
         | https://pyfound.blogspot.com/2020/04/all-strings-become-f-st...
        
         | DylanDmitri wrote:
         | Yeah it's a backwards compatibility issue, wouldn't be
         | surprised if they make this change in Python4
        
       | rdtsc wrote:
       | > However, once you start using several parameters and longer
       | strings, your code will quickly become much less easily readable
       | [...] `"Hello, %s %s. You are %s. You are a %s ...`
       | 
       | Minor correction: % formatting allows specifying names for
       | dictionary keys too:                   In [1]: "%(a)s and %(b)s"
       | % {"a":"A", "b":"B"}         Out[1]: 'A and B'
       | 
       | In fact I had never switched to using str.format as it just never
       | added enough benefit for me over the old %-based formatting.
       | 
       | But I do like f-strings and am using them quite a bit. Calling
       | functions or methods inside f-strings is something I had no idea
       | was possible. That is pretty neat:                   >>> name =
       | "Eric Idle"         >>> f"{to_lowercase(name)} is funny."
       | 'eric idle is funny.'
        
         | mixmastamyk wrote:
         | f"{name.lower()} is funny."
        
           | rdtsc wrote:
           | The article demonstrates both methods and functions. I just
           | pasted the function example, but without the showing the
           | function definition itself as it's fairly obvious :-)
        
       | japhyr wrote:
       | I learned this nice syntax from a tweet yesterday:
       | >>> import datetime         >>> now = datetime.datetime.now()
       | >>> f"Today is {now:%m/%d/%Y}."         'Today is 01/20/2021.'
       | 
       | No need for now.strftime() in simple string output!
       | 
       | https://twitter.com/mariatta/status/1351359518316216321
        
       | gh123man wrote:
       | This reminds me of Swift's string formatting syntax:
       | let name = "Bob"       print("Hi my name is \(name)")
       | 
       | Which I always quite liked. I found myself missing this when I
       | moved on to Rust and Go.
        
         | ausbah wrote:
         | Kotlin is even simpler with statements like "hello $variable"
         | or "hello ${function()}"
        
         | blackrock wrote:
         | This overloads the backslash \\().
         | 
         | Which is usually used for escaping characters. Like, \n for new
         | line.
         | 
         | So, you may end up with code like:                 print("Hi.
         | \nMy name is \(name).")
        
       | CJefferson wrote:
       | The thing which annoys me most about f strings is I can't build
       | them at runtime, which means I can't just learn/teach f strings.
       | 
       | While I know why building f strings is forbidden (they can run
       | arbitrary code), I'm happy to take the risk.
        
         | epage wrote:
         | Delayed formatting was brought up in the PEP but was rejected.
         | That made me a little sad.
        
         | wodenokoto wrote:
         | Doesn't calling .format on a string do the exact same thing as
         | an f-string?
        
         | throwaway894345 wrote:
         | I mean it's Python, so you can do anything:
         | >>> fstring="Hello, {\"world\"}"         >>>
         | eval(f"print(f'{fstring}')")         Hello, world
        
       | bjoli wrote:
       | When it comes to string formatting I have recently found my
       | absolute favourite utility of all time: Scheme's SRFI-166. It is
       | a combinator based string formatting utility that is user
       | extensible (with verbosity worthy of being in every scheme!):
       | https://srfi.schemers.org/srfi-166/srfi-166.html
        
       | kazinator wrote:
       | A couple of years ago I wrote some Python code which took
       | advantage of this syntax. Then it turned it had to run in an
       | environment without it.
       | 
       | I wrote a simple Awk script to convert Python with f-string
       | syntax to syntax without it.
       | 
       | (The program had a function to do a more or less proper lexical
       | analysis job; not some flimsy regex substitution hack.)
        
         | renewiltord wrote:
         | Should you ever find yourself in a situation like that,
         | https://github.com/python-rope/rope might help.
        
       | psychoslave wrote:
       | So far Ruby provided me the best user experience regarding string
       | interpolation, and it owes a large part of it to Perl.
       | 
       | Squiggly heredoc is something I am unaware of in any other
       | general programming language.
        
       | driverdan wrote:
       | F-strings have been around for years and this article is at least
       | a few years old. I'm curious why this is coming up now.
        
         | t-writescode wrote:
         | People finally forced to move off Python 2.7?
        
         | EForEndeavour wrote:
         | I wonder if the submitter was inspired by this tweet that went
         | viral (by python standards) yesterday:
         | https://twitter.com/mariatta/status/1351359518316216321
        
           | mixmastamyk wrote:
           | Capital f-strings should have not been allowed in my opinion.
        
       | abdusco wrote:
       | Not mentioned in the article, but with Python 3.8, f-strings have
       | gained the ability to print debug information using `=`
       | specifier.                   name = 'world'         print(f'hello
       | {name.upper()=}')
       | 
       | outputs:                   hello name.upper()='WORLD'
       | 
       | It's small, but very useful in debugging an issue or logging
       | something to the console.
       | 
       | https://docs.python.org/3/whatsnew/3.8.html#f-strings-suppor...
        
         | richardARPANET wrote:
         | Way better -> https://pypi.org/project/q/
        
         | cabalamat wrote:
         | That's something I didn't know, but will know be using.
        
       | noncoml wrote:
       | I can't say I like the f" syntax much. I think JS's backtick is
       | better.
       | 
       | Other than that, I agree, much better than % and less verbose
       | than .format.
       | 
       | It's just the f" or f' that doesn't sit right with me
        
         | dharmab wrote:
         | It's consistent with other strings in Python like r-strings and
         | the older u-strings.
        
           | teddyh wrote:
           | And b-strings.
        
         | mixmastamyk wrote:
         | I agree it's not the most beautiful, but it was the best choice
         | given the requirements. Basically, it had to be explicit,
         | concise, use unused ASCII syntax, and not be too cryptic or
         | incompatible. Other quote types or backticks were not available
         | or an option.
         | 
         | (I spent a lot of time thinking about it, and put the idea
         | forward on python-ideas. Though string interpolation is nothing
         | new of course.)
        
         | patrec wrote:
         | I think you are right to prefer JS's backtick notation, but not
         | in your reason.
         | 
         | The main problem with python's f" syntax is that it's just a
         | very complex, non-extensible hack whereas in javascript you can
         | prefix a tag to specify how the interpolation happens.
         | 
         | Instead of this, f-strings have a lot of hardcoded and often
         | broken behavior which can't be fixed let alone customized. For
         | example, you can specify a field width, but it will not even
         | work properly even in a fixed-width context, because of quite
         | common things like emojis or CJK or combining characters don't
         | have their width computed correctly.
        
           | mixmastamyk wrote:
           | It's not a hack or broken. The formatting language existed
           | before f-strings and is somewhat a separate issue.
           | 
           | I'm not sure I expect it to handle every Unicode nuance
           | either, when there are modules in the stdlib for that.
        
         | ericvsmith wrote:
         | I've put together a proposal to have all strings be f-strings
         | by default.
         | 
         | Then you could drop the "f" prefix. I also propose adding a "p"
         | prefix (for "plain") to remove the f-string parsing behavior.
         | 
         | I talked about it at the last Python core sprint, and it only
         | got lukewarm support, so I'm not sure I'm going to pursue it.
        
         | nurpax wrote:
         | Yup, especially as you often need to access dict's with
         | foo["field"] and you get a syntax error if the f-strings is
         | also f"". JavaScript backtick syntax doesn't lead to this extra
         | syntactic friction.
        
           | ericvsmith wrote:
           | This is because of how f-strings were initially implemented:
           | I piggy-backed them off of "regular" strings, then post-
           | parsed inside that string. But the restriction is that the
           | entire f-string (after the f) needs to be a valid regular
           | Python string.
           | 
           | Since this: "this is a "regular" string" isn't valid, then
           | neither is this: f"dict lookup: {d["key"]}"
           | 
           | However, we've talked about changing f-string parsing from a
           | "post-process regular strings" mode, to instead having the
           | tokenizer and parser themselves aware of f-strings. When we
           | do that, the f-string example above will work.
        
           | ziml77 wrote:
           | I'm surprised it works like that in Python. C# has similar
           | interpolated strings but there it's legal to embed quotation
           | marks within the curly brackets. Though I guess it's less
           | necessary in Python since you can just use the other type of
           | quote inside.
        
           | quietbritishjim wrote:
           | You can use any of                   f"{foo['field']}"
           | f'{foo["field"]}'         f"""{foo["field"]}"""
           | 
           | (I see from your carefully worded first sentence that you
           | already knew this but still find it annoying, but I'll leave
           | this here for any that aren't aware.)
        
             | mixmastamyk wrote:
             | Yes, and anyone who has written a "one-liner" at the
             | command line is familiar with it. Wouldn't say it is a big
             | problem.
        
           | wskinner wrote:
           | This is easily avoidable in python by using single quotes for
           | the outer string and double quotes for the inner string, or
           | vice versa. Or, use triple quotes for the outer string.
        
             | dragonwriter wrote:
             | Yeah, if you get to the level of nesting where having
             | available quotes is an issue, you really need to break it
             | up into multiple expressions.
        
         | pansa2 wrote:
         | I quite like the idea of using double-quotes for format strings
         | and single-quotes for normal strings.
         | 
         | This isn't sufficient on its own, though - what about raw
         | strings? Perhaps use "" for format strings, '' for raw strings
         | and get rid of normal strings altogether?
        
       ___________________________________________________________________
       (page generated 2021-01-20 23:01 UTC)