Print variable and a string in python
How do you print a variable along with a string in Python? What different methods, like concatenation, f-strings, or format(), can be used to display values clearly?
When coding in Python, you’ll often need to display variables alongside descriptive text. This raises the question: “How do I print a variable and a string in Python?” Fortunately, Python offers multiple ways to achieve this, ranging from simple concatenation to modern f-strings.
Method 1: String Concatenation
You can join strings with the + operator, but you must convert non-strings using str():
name = "Alice"
print("Hello " + name)
Method 2: Comma in print()
The print() function accepts multiple arguments separated by commas. It automatically adds spaces and converts variables to strings:
age = 25
print("Age is", age)
Method 3: str.format() Method
Introduced in Python 3, this method allows placeholders inside strings:
score = 95
print("Your score is {}".format(score))
Method 4: f-Strings (Best and Recommended)
Available in Python 3.6+, f-strings provide the cleanest syntax for embedding variables directly:
city = "New York"
print(f"I live in {city}")
Method 5: Percent Formatting (Older Style)
Though less common today, you can use %:
price = 9.99
print("Price: %.2f" % price)
Key Takeaway:
While Python supports multiple methods, f-strings are the most modern, readable, and efficient way to print variables with strings. They make your code concise and easy to maintain.