String Concatenation

String Concatenation

Four Ways to Print Variables in Strings

So you have a variable?or three?that you want to include as part of a string. Have no fear, there are many ways to accomplish this in Python. Whichever you choose is up to your personal preference. I?ll share my method of choice down at the end of the tutorial.

An oldie-but-goodie, we have to include the simplest method which is concatenating a variable and string together.

This method is probably the very first one you learned, but you?ve probably moved on as well. The syntax overhead plus meticulous management of spaces makes string concatenation a hassle.

String Literal Modifiers

One of the Python string literal modifiers is the f modifier, which stands for format and allows you to embed Python directly in a string within curly braces.

This method is going to get you as close to the full string as possible. It may go unnoticed without mention, so I?ll be explicit and let you know that within the curly braces you can perform operations, call functions, etc. Just be careful not to do too much or your code will suffer from readability.

The .format() Method

You may have come across the .format() method of the String class in other languages as well. This technique uses curly brace placeholders that can also include data type conversions and formatting.

The ability to customize the appearance of numeric data is helpful here. Notice in the example I limit the score?a calculated value?to a two-decimal float.

Using % Formatting

The final technique involves a placeholder percent symbol followed by a letter representing the appropriate data type. After the string, a % connects the list of variables to be mapped to each placeholder.

This method keeps the syntax within the string to a minimum while still having some control over format such as truncating decimals by typecasting as an integer.

My Preferred Method

It may be a bit of a lame answer but I use all three of the methods outside of string concatenation. They each have a place as far as I?m concerned, although I?m slowly breaking the habit of using % formatting. I still use that method for things like URLs where I want a clear picture of the string and there is minimal data manipulation.

My new default is to use the f-string literal technique. It takes time to remember to type the leading f but I?m getting better. Finally, if I need to format numbers, specifically decimals, I?ll bring out the .format() method. This is the most flexible of the four, however, it?s a bit too much syntax for my liking so I only use it when necessary.

What?s your preferred way of including variables in strings? Why? Leave your comments below and thanks for reading through!

23