w3resource

Python: Add a prefix text to all of the lines in a string

Python String: Exercise-28 with Solution

Write a Python program to add prefix text to all of the lines in a string.

Python String Exercises: Add a prefix text to all of the lines in a string

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 that includes indentation.
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 the common leading whitespace (indentation) from 'sample_text'.
text_without_Indentation = textwrap.dedent(sample_text)

# Print an empty line for spacing.
print()

# Print the 'text_without_Indentation', which is the 'sample_text' with indentation removed.
print(text_without_Indentation)

# 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: Add a prefix text to all of the lines in a string

Python Code Editor:

Previous: Write a Python program to remove existing indentation from all of the lines in a given text.
Next: Write a Python program to set the indentation of the first line.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://198.211.115.131/python-exercises/string/python-data-type-string-exercise-28.php