w3resource

Python: Display formatted text as output


Display formatted text (width=50).

Write a Python program to display formatted text (width=50) as output.

Sample Solution:

Python Code:

# Import the 'textwrap' module, which provides text formatting capabilities.
import textwrap
# Define a multi-line string 'sample_text' with a text content.
sample_text = '''
  Python is a widely used high-level, general-purpose, interpreted,
  dynamic programming language. Its design philosophy emphasizes
  code readability, and its syntax allows programmers to express
  concepts in fewer lines of code than possible in languages such
  as C++ or Java.
  '''

# Print an empty line for spacing.
print()

# Use the 'textwrap.fill' function to format the 'sample_text' with a line width of 50 characters.
# This function wraps the text to fit within the specified width and prints the result.
print(textwrap.fill(sample_text, width=50))

# Print an empty line for spacing.
print()

Sample Output:

 Python is a widely used high-level, general-                                                               
purpose, interpreted,   dynamic programming                                                                   
language. Its design philosophy emphasizes   code                                                             
readability, and its syntax allows programmers to                                                             
express   concepts in fewer lines of code than                                                                
possible in languages such   as C++ or Java.    

Flowchart:

Flowchart: Display formatted text as output

For more Practice: Solve these Related Problems:

  • Write a Python program to format a paragraph so that each line does not exceed 50 characters using the textwrap module.
  • Write a Python program to reformat input text to a fixed width of 50 characters per line with proper word wrapping.
  • Write a Python program to implement custom logic to break a string into lines of at most 50 characters.
  • Write a Python program to display a given block of text with each line justified to a width of 50 characters.

Go to:


Previous: Write a Python program to create a Caesar encryption.
Next: Write a Python program to remove existing indentation from all of the lines in a given text.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.