Python: Set the indentation of the first line
Python String: Exercise-29 with Solution
Write a Python program to set the indentation of the first line.
Sample Solution:
Python Code:
# Import the 'textwrap' module, which provides text formatting capabilities.
import textwrap
# Define a multi-line string 'sample_text' with 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.
'''
# Use 'textwrap.dedent' to remove common leading whitespace and 'strip' to remove any trailing whitespace.
text1 = textwrap.dedent(sample_text).strip()
# Print an empty line for spacing.
print()
# Use 'textwrap.fill' to format and wrap the 'text1' string to a line width of 80 characters.
# The 'initial_indent' and 'subsequent_indent' parameters control the indentation, which is adjusted here.
print(textwrap.fill(text1,
initial_indent='',
subsequent_indent=' ' * 4,
width=80,
))
# 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:
Python Code Editor:
Previous: Write a Python program to add a prefix text to all of the lines in a string.
Next: Write a Python program to print the following floating numbers upto 2 decimal places.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/string/python-data-type-string-exercise-29.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics