Exercise 2-7 Solution – Python Crash Course Chapter 2: Variables and Simple Data Types

 

📘 Python Crash Course – Chapter 2: Variables and Simple Data Types – Exercise 2-7 Solution

Welcome to another solution from Python Crash Course by Eric Matthes.


📝 Exercise 2-7

Task: Store a person’s name, and include some whitespace characters at the beginning and end of the name .Print the name once, so the whitespace around the name is displayed . Then print the name using each of the three stripping functions, lstrip(), rstrip(), and strip()

✅ Solution Code:


name ="        jarvis       "
print(name)
print(f'rstrip : {name.rstrip()}')
print(f'lstrip : {name.lstrip()}')
print(f'strip : {name.strip()}')

🧠 Code Explanation:

This Python code demonstrates how to handle and remove whitespace from a string using different string methods. Here's how it works:

  1. Store a name with whitespace:

    The variable name is assigned the string " jarvis ", which includes whitespace at the beginning and end.

  2. Print the name with whitespace:

    The print() function is used to display the name as it is, including the surrounding whitespace.

  3. Remove trailing whitespace:

    The rstrip() method is used to remove whitespace from the right side of the string, and the result is printed.

  4. Remove leading whitespace:

    The lstrip() method is used to remove whitespace from the left side of the string, and the result is printed.

  5. Remove all surrounding whitespace:

    The strip() method is used to remove whitespace from both sides of the string, and the result is printed.

🔍 Output:


        jarvis       
rstrip :         jarvis
lstrip : jarvis       
strip : jarvis

📚 Related Exercises from Chapter 2:


🔗 Connect With Us:

“The only way to learn a new programming language is by writing programs in it.”
– Dennis Ritchie

📌 Tags: #Python #PythonCrashCourse #CodingForBeginners #LearnPython #PythonProjects #PythonTips

Previous Post Next Post

Contact Form