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

“In the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”— Only Python

πŸ“Œ Follow Us And Stay Updated For Daily Updates

Comments