How To Print A String In Python

In this tutorial, we will learn how to print a string in Python. String-printing is an essential operation in programming, and Python makes it easy to accomplish.

With this knowledge, you’ll be able to display any text or information to the console or output device, allowing for easier debugging and interaction with users.

Step 1: Understanding the ‘print()’ Function

The built-in Python function that is used for printing a string is print(). By default, it outputs your string, along with a new line character after the string. Simply pass the string you want to print as an argument to the print() function, and Python will take care of the rest.

Step 2: Printing a Simple String

Here’s a simple example demonstrating how to print a string in Python:

This will output the following to the console:

Hello, World!

Step 3: Using Escape Characters

Sometimes, you may want to print a string with special characters, like single or double quotes, or even a new line inside your string. For these cases, use escape characters. The backslash (\) is used as an escape character in Python.

Here’s an example of using escape characters to print a string with double quotes and a new line:

This will output:

He said, "Hello, World!"
This is a new line.

Step 4: Using String Formatting

You can also use string formatting to print a string with dynamic values. One of the most popular and powerful methods in Python is the f-string formatting. This allows you to embed expressions in your string by wrapping them in curly braces ({}) and prefixing the string with an ‘f’ or ‘F’.

Here’s an example of using f-string formatting to print a personalized greeting:

This will output:

Hello, Alice!

Step 5: Combining Strings and Other Data Types

You can also combine strings with other data types using the str() function or f-strings. Here’s an example of printing a string combined with an integer:

Alternatively, you can use f-strings to achieve the same result:

Both of these will output:

There are 5 cookies.

Full Code Example

Here’s the complete code that includes all the examples we covered above.


Now that you have learned how to print a string in Python, you can effectively display text and information to users or debug your code as needed. Remember to practice using the print() function, escape characters, string formatting, and combining strings with other data types in your Python programming journey.