How To Print ASCII Text In Python

Printing ASCII text in Python is a simple and powerful aspect of programming, especially when it comes to designing console-based applications or creating eye-catching banner text. In this tutorial, you will learn how to print ASCII text in Python.

Step 1: Create an ASCII text file

Create a ascii_text.txt file containing your soon-to-be-converted ASCII text. For this example, we’ll use the following text:

_____ ____  _______ ____
|   | |  ||       \  |  |
|   | |  ||  ----  |  |  |
|___| |__||__|__|__|__|__|

Save this text in a file named ascii_text.txt.

Step 2: Read the ASCII text file in Python

In order to print the ASCII text in Python, we’ll need to read the contents of the ascii_text.txt file and print it on the screen. We can achieve this using the open function and a for loop:

Let’s examine the code:

  • We use the with statement to open the file ascii_text.txt in read mode, represented by "r". This context manager ensures that the file is closed automatically once the operations within the block are completed.
  • We then iterate over each line in the file using a for loop.
  • We print the line using the print function, removing the newline character at the end of each line using the strip() method.

Now run the code, and your output should look like this:

_____ ____  _______ ____
|   | |  ||       \  |  |
|   | |  ||  ----  |  |  |
|___| |__||__|__|__|__|__|

Step 3: Obtain user input (optional)

For a more interactive experience, you can ask users to provide a file name containing their ASCII art, and then display the provided text. This can be achieved using the input function:

When running the code, the user will now be asked to provide the name of an ASCII text file before displaying the text on the screen.

Full code

Output

_____ ____  _______ ____
|   | |  ||       \  |  |
|   | |  ||  ----  |  |  |
|___| |__||__|__|__|__|__|

Conclusion

In this tutorial, we learned how to print ASCII text in Python. This simple yet powerful feature can help you create visually appealing console applications or help produce unique log messages, banners, or headings in your Python projects. Happy coding!