Python: String Formatting

When concatenating strings, Python has (prior to 3.6) avoid the direct variable injection into a string, which you can see in languages like Groovy, Ruby, and so on. Prior to 3.6, Python 3 introduced a mechanism to add strings using the formatting method:

print("hello {0} your account number is {1}".format("Brian", 1234))
# the above code will output: hello Brian your account number is 1234

I recently was taking a data science course and the instructor used a formatter I wasn’t familiar with:

name = "Brian"
account_number = 1234
print(f"hello {name} your account number is {account_number}.")

Using the f” formatter allows direct injection of the variable names, which is similar to Groovy, PHP, and many other languages. This syntax however is not backwards compatible with versions of Python prior to 3.6.

Another useful string formatter is the raw formatter:

print(r"My files are on /var/log/tomcat")

The above code will be read as though you escaped the special character “/”, so it will print it literally as it is written.

About Author /

Leave a Comment

Your email address will not be published.

Start typing and press Enter to search