How can I print variable and string on same line in Python?
Print a variable with a string on the same line using the print()
function combined with + for concatenation, or preferably, an f-string for clean, manageable and easy-to-read code:
Too cool for school: f-strings
In Python 3.6 and above, f-strings provide a snappy way to include the value of expressions, variables and functions inside a string by using {}
braces:
With f-strings, you can also include expressions and functions directly in your string:
When you need a format: using .format()
The str.format()
method is versatile, flexible, and nearly as readable as f-strings. The .format()
method is your secret weapon when compatibility with Python 2 is necessary:
Hang on - there's more! Tweak the representation of objects inside the string. Say hello to padding, alignment, and other format specifiers:
Concatenation: going back to basics
When the string is static (does not change), you can simply use + to concatenate the string and variable:
Remember, the str()
function is your friend for converting non-string variables before concatenation:
"%s" me up: printf-style
If you're a fan of C or feeling a bit nostalgic, Python supports printf-style string formatting using %
. Although a bit old-fashioned, this method is still widely used:
Tips & Tricks for polished output
For polished and clean printouts, keep these trade secrets at your fingertips:
Formatting floats
Use :.nf
where n is a digit to control decimal precision in .format()
and f-strings:
This will help with the annoying floating point precision hiccups that keep you up all night 🛌💤!
String quotes
Strings are enclosed in single (' ') or double (" ") quotes. Single quotes are useful to include double quotes within the string and vice versa:
For exceptionally long strings involving both quotation forms, triple single or double quotes are your best friend!
Was this article helpful?