Formatted String Literals
Embed Variables in Strings
One of the features I like in PHP is the heredoc string syntax because developers can include inline variables. This makes it easy to include variable within content.
Here's a sample snippet:
$content .= >>> end_here Hello, $world! end_here
In Python 3, you have the same functionality by using f-strings (otherwise known as Formatted String Literals). To enable this you simply prefix the string with an 'f'. For example:
content += f""" Hello {world}! """[1:-1]
or
print(f"Hello, {fname}, thank you for your input.")
Check out the Detailed Python Instructions on Formatted String Literals.
Remove the First Line
If you get in the habit of starting text on the line immediately below the start of the heredoc, you should add a [1:-1] at the end of the heredoc. This is because in Python the heredoc actually starts after the third quote. This means that if you use heredoc to generate lists, the first item will be empty. Yikes!
I would recommend setting up a code snippet with the [1:-1] at the end so you don't forget.
In this example: I created a list of restaurants using a heredoc, converted it to a list, randomized the list order, and then displayed the results:
foodchains = """ Taco Bell Boston Market MacDonalds Sonic Fatburger Jack-In-The-Box """[1:-1] fastfood = foodchains.splitlines() random.shuffle(fastfood) print(f'Best place to eat is {fastfood[1]} and {fastfood[2]} then {fastfood[3]}')
Fix the Unicode Error
If you encounter the dreaded "UnicodeEncodeError" from a database import, you can easily fix it by using a simple convert trick within your string. You can apply a modifier to the Formatted String to convert the value before it gets outputted.
In this example the display text will be convert to ascii():
print (f'Name: {databaseName!a})
Another useful format command is '!s' which will convert the text to string.
Adding Commas to Digits
When you have a large number and want to "commify" the output, simply use this trick with formatting string literals:
totalSales = 20000 print(f'Formal: {totalSales:,.2f} and Simple: {totalSales:,}') // Formal: 20,000.00 and Simple: 20,000
Execute Expressions
You can easily perform commands within the f-string. In this example, I am displaying the current date:
## Display Date as Month, ##, #### (Without the leading zero in days.)
from datetime import date
print(f'Today is: {date.today().strftime("%B %-d, %G")}')
## Another way:
import datetime
dt = datetime.datetime.now()
print(f'{dt:%A} {dt:%B} {dt.day}, {dt.year}')
Another example, making sure that the display name is properly capitalized.:
## Make Name Uppercase content += """ Welcome to the Forum {FirstName.capitalize()}! """[1:-1]