+ 3
My first F string code
Is this f string code fine or is there's a better way to write it? https://sololearn.com/compiler-playground/cDQKdRr5D7Yi/?ref=app
8 Réponses
+ 7
There are many other ways to format the text like this, but f-strings are usually the most convenient and most readable, they are also considered the most "pythonic".
Qualifying as "best", requires more context.. for example "best for performance" or "best for readability".
But don't worry about it too much. There are many coding styles, use the one that is most comfortable for you. And you can improve or change it over time, as you learn more.
+ 7
Rebecca Harris ,
you could make the code a bit more *general* by using the input() function instead of having a *hard coded variable*:
name = input() or 'Eric'
print(f"Hello {name}, would you like to learn Python today?")
+ 6
Your code is good.
The point of f string is that you can insert many variables, control their format, and do calculations, while having nice looking code.
name = "Eric"
print(f"Hello {name * 3}, would you like to learn Python today?")
+ 5
it's fine.
+ 4
Rebecca Harris
If you don't plan on using name again later on in your program, you can put input() inside the f string...
print(f"Hello {input()}, would you like to learn Python today?")
going down the f-string rabbit hole, I found that you can put f string inside f string, and use chr(10) to cheat the no backslash rule and put in a \n inside the brackets, so you can add a nice prompt in your input and add a newline '\n' after the prompt. All in one complicated nested f-string 😅....
print(f"\nHello {input(f'What is your name?{chr(10)}')}, would you like to learn Python today?")
But these are party tricks. As with everything, keeping things simple should be the priority.
+ 3
Rebecca Harris ,
The Python syntax looks perfect to me. I think the English syntax should look like this.
Hello, Eric. Would you like to learn Python today?
Here's my tip about using nested curly braces (a different purpose than Bob_Li 's example, but the same rule).
https://sololearn.com/compiler-playground/c5Bt5I46DZpg/?ref=app
+ 2
Bob_Li ,
Pydroid 3 now runs Python 3.11.4, which means I can try out the new switch compound statement.
I searched, and I see what you mean. Python 3.12 has a bunch of f-string updates from PEP 701.
https://docs.python.org/3/whatsnew/3.12.html#pep-701-syntactic-formalization-of-f-strings