π 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:
-
Store a name with whitespace:
The variable
name
is assigned the string" jarvis "
, which includes whitespace at the beginning and end. -
Print the name with whitespace:
The
print()
function is used to display the name as it is, including the surrounding whitespace. -
Remove trailing whitespace:
The
rstrip()
method is used to remove whitespace from the right side of the string, and the result is printed. -
Remove leading whitespace:
The
lstrip()
method is used to remove whitespace from the left side of the string, and the result is printed. -
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:
- ➤ Exercise 2-1 | Simple Message Part 1
- ➤ Exercise 2-2 | Simple Messages Part 2
- ➤ Exercise 2-3 | Personal Message
- ➤ Exercise 2-4 | Name Cases
- ➤ Exercise 2-5 | Famous Quote
- ➤ Exercise 2-6 | Famous Quote 2
- ➤ Exercise 2-7 | Stripping Names
- ➤ Exercise 2-8 | Number Eight
- ➤ Exercise 2-9 | Favorite Number
- ➤ Exercise 2-10 | Adding Comments
- ➤ Exercise 2-11 | Zen of Python
π 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
πTrending Topics
π Connect With Us:
“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
Post a Comment