Strip in Python: Explained Python Strip Function with Examples
Updated on Aug 18, 2023 | 8 min read | 2.1k views
Share:
For working professionals
For fresh graduates
More
Updated on Aug 18, 2023 | 8 min read | 2.1k views
Share:
Table of Contents
The strip function in Python is a useful tool for removing leading and trailing whitespace characters such as spaces, tabs, and newlines from strings. This article will look at the strip() method and its variants, such as lstrip() and rstrip(), using real examples. We’ll further demonstrate the strip() function’s adaptability by showcasing its efficacy in different situations.
By the end of this article, you will understand how to use this function effectively to modify strings and improve your Python programming skills.
The strip method in Python accepts one optional parameter:
characters: This argument indicates which characters should be eliminated from the string’s starting and end. If no arguments are passed, the strip() function will, by default, remove all leading and following whitespace characters.
The strip() method has the following syntax:
string.strip([characters])
Examples:
Without any parameters, use strip():
text = "Hi, Athar "
result = text.strip()
print(result)
Output: “Hi, Athar”
2. Using the characters parameter with a strip():
text = "++Hi, Athar++"
result = text.strip("+")
print(result)
Output: “Hi, Athar!”
The leading and trailing plus (+) marks were eliminated from the string.
Check out our free courses to get an edge over the competition.
The strip function in Python returns a string that only depends on the parameter.
1. If no character parameters are specified, all whitespaces at the beginning and end of the string are truncated, and the original string is returned with no white space at the beginning and end.
2. If no character parameters are specified, and there are no white spaces at the beginning and end of the text, the original string is returned.
3. If a character parameter is supplied, and the appropriate character is found at the beginning and end of the string, it will be removed, and the remainder of the string will be returned.
4. If a character parameter is supplied, and the matching character is not found at the beginning or end of the string, the string will be returned as it is.
Example of the strip() being used and the result type is verified:
text = " Hi, Tim"
trimmed_text = text.strip()
print(trimmed_text)
Output: “Hi, Tim”
# Verifying the return type
print(type(trimmed_text)) # Output: <class 'str'>
The strip() method, as demonstrated in the example, returns a string, which can then be placed in a variable or used directly in further operations.
The terms “Python trim string” and “strip()” are sometimes used interchangeably because the strip() method successfully trims the leading and trailing spaces or specified characters from the string.
Learn data science courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
The strip method in Python only accepts the ‘String’ data type. This means the strip will only function on strings, not other data types.
Here’s what happens if you try to use strip() on an invalid data type:
# Invalid data type: Integer
number = 32
try:
result = number.strip()
except TypeError as e:
print("Error:", e)
# Invalid data type: List
my_list = [5, 2, 7]
try:
result = my_list.strip()
except TypeError as e:
print("Error:", e)
Output:
Error: 'int' object has no attribute 'strip'
Error: 'list' object has no attribute 'strip'
As given above, attempting to use strip() on an integer or a list results in a TypeError since these data types lack the strip() method.
Only use the strip() method on string objects to prevent this mistake. If necessary, you can convert other data types to strings before using strip(). As an example:
# Converting an integer to a string and then using strip()
number = 32
string_number = str(number)
result = string_number.strip()
print(result)
Output: “32”
The strip method in Python removes whitespace characters (spaces, tabs, and newlines) from a string. It is a popular approach for cleaning up strings, especially when working with user input, reading data from files, or processing data from external sources that may contain unnecessary whitespaces.
The strip() function is widely used for the following reasons:
Here’s an example of how to use the strip function in Python and rstrip function in Python:
text_with_spaces = " Hi, Tim! "
cleaned_text = text_with_spaces.strip()
print(cleaned_text)
Output: “Hi, Tim!”
cleaned_text_rstrip = text_with_spaces.rstrip()
print(cleaned_text_rstrip)
Output: ” Hello, World!”
Strip in Python eliminates both leading and trailing spaces in this example, whereas rstrip() removes only the trailing spaces, leaving the leading spaces alone. These methods provide efficient string cleanup and manipulation in various Python applications.
On the other hand, if you wish to enhance your data science skills going forth, you can check out upGrad’s Post Graduate Diploma in Data Science & AI!
Choosing the best software development programme is influenced by several factors, including goals, background, preferred programming languages, and the exact sector of software development you wish to pursue. Consider the following common alternatives:
Institution Computer Science Degree: Pursuing a computer science degree from a reputed institution may be an excellent option if you want a full education in software development and theoretical computer science topics.
Coding and Bootcamps: Bootcamps are intensive, short-term training programs that emphasise practical coding abilities. They are a good choice if you want to quickly learn specific programming languages or technologies and begin a career in software development.
Online Learning Platforms: Numerous online platforms provide self-paced software development courses and tutorials. Platforms such as upGrad offer a diverse selection of courses ranging from basic to advanced levels, covering a variety of programming languages and software development topics.
You can accelerate your career with upGrad’s course Executive PG Program in Data Science & Machine Learning from University of Maryland. Identify insights, improve your prediction skills, and make better data-driven business decisions.
Apprenticeship Programmes: Certain companies provide apprenticeship programmes through which you can work and learn on the job. This allows you to obtain hands-on experience while being guided and mentored by experienced developers.
In conclusion, the strip in Python is a powerful tool for eliminating leading or trailing whitespace or specified characters from strings. It’s useful for data validation, sanitising user input, and processing text files. The optional characters argument allows for the removal of specific characters. Understanding strip function in Python improves string manipulation by maintaining data consistency and precise comparisons. Use it to optimise code and build strong applications.
Begin your data science career with upGrad’s most popular online Executive Post Graduate Programme in Data Science offered by IIITB. This programme is comparable to a one-year Postgraduate Diploma, offering detailed insights into the world of data science to establish a skyrocketing career!
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources