w3resource

Python: Set the indentation of the first line


Set first line indentation.

Write a Python program to set the indentation of the first line.

Python String Exercises: 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:

Flowchart: Set the indent of the first line

For more Practice: Solve these Related Problems:

  • Write a Python program to indent only the first line of a multi-line string by a specified number of spaces.
  • Write a Python program to add a custom indentation to the first line of text while leaving subsequent lines unchanged.
  • Write a Python program to use string concatenation to apply a prefix of spaces to the first line of a paragraph.
  • Write a Python program to implement a function that sets the first line indentation based on user input.

Go to:


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.

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.