Are you looking to print a statement in Python without the enclosing brackets? This tutorial will help you to learn how to print without brackets in Python.
This method is particularly handy when you want to enhance the readability of your output statements or when you want to combine different types of data in a single print statement.
Step 1: Start with the Basic Print Function
In Python, the basic print()
function is used to display output to the console. The syntax of the function is:
1 |
print(value, ..., sep=' ', end='\n') |
– value
represents the data to be printed.
You can add multiple values separated by commas, and the data will be printed together with the default separator (a space). The sep
parameter in the print()
function can be customized to use a different separator. The end
parameter denotes the character to be added at the end of the print statement, and its default value is a newline character.
Step 2: Using formatted string literals
Formatted string literals, also known as f-strings, are a convenient way to embed expressions inside string literals. To print without brackets, you can utilize f-strings in your print statements. By enclosing expressions inside curly brackets {} and prefixing the string with an f or F character, you can easily print without brackets.
To demonstrate this, let’s create a simple program that prints a user’s first and last name without brackets:
1 2 3 4 5 |
first_name = "John" last_name = "Doe" # Using f-string to print without brackets print(f"{first_name} {last_name}") |
Output:
John Doe
Step 3: Printing Multiple Variables Without Brackets
To print multiple variables without brackets, you can combine f-strings with the sep
and end
parameters in the print function. Here’s an example to illustrate this:
1 2 3 4 5 |
name = "Jane" age = 30 # Using f-string with sep and end parameters print(f"My name is {name}", f"and I am {age} years old", sep=', ', end='.') |
Output:
My name is Jane, and I am 30 years old.
Full Code
1 2 3 4 5 6 7 8 9 10 11 |
first_name = "John" last_name = "Doe" # Using f-string to print without brackets print(f"{first_name} {last_name}") name = "Jane" age = 30 # Using f-string with sep and end parameters print(f"My name is {name}", f"and I am {age} years old", sep=', ', end='.') |
Conclusion
In this tutorial, you learned how to print without brackets in Python using formatted string literals (f-strings). Now you can improve the readability of your output statements and easily print data of different types without brackets in your Python programs.