For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
The strip() function in Python helps clean strings by removing unwanted spaces or characters from both ends of the text. This function is widely used in data preprocessing, form validation, and string formatting. Whether you're handling user input or cleaning file data, understanding how the strip() function in Python works is essential.
In this article, we will explore the purpose and usage of the strip() function in Python. You will learn its syntax, various real-life examples, common errors to avoid, and the best situations where this function proves useful. By the end, you will have a solid grasp of how and when to use the strip in Python effectively.
Pursue our Software Engineering courses to get hands-on experience!
The strip() function in Python is used to remove unwanted characters from the beginning and the end of a string. By default, it eliminates leading and trailing whitespaces. However, you can also pass specific characters as arguments to remove them instead.
This function is extremely helpful in text processing tasks like cleaning user input, formatting data, or removing extra symbols from strings. It does not alter the original string but returns a new, cleaned version.
Keypoint:
Take your skills to the next level with these top programs:
Here is the general syntax of strip in Python:
string.strip([chars])
Explanation:
string: The string you want to clean.
chars (optional): A string of characters to remove from both the beginning and end of the original string. If not provided, it removes all types of leading and trailing whitespaces such as spaces, tabs (\t), and newlines (\n).
Note: This function is applied only to string data types.
Here’s a simple example to understand how the strip() function works with and without arguments:
text1 = " Learn Python "
cleaned_text1 = text1.strip() # Removes whitespace from both ends
# Example 2: Using strip() with a character argument
text2 = "###DataScience###"
cleaned_text2 = text2.strip("#") # Removes '#' from both ends
# Display the results
print("Without Argument - Before:", repr(text1))
print("Without Argument - After:", repr(cleaned_text1))
print("With Argument - Before:", repr(text2))
print("With Argument - After:", repr(cleaned_text2))
Output:
Without Argument - Before: ' Learn Python '
Without Argument - After: 'Learn Python'
With Argument - Before: '###DataScience###'
With Argument - After: 'DataScience'
Explanation:
The strip() function is often used in input validation, reading data from files, or preprocessing strings before storing them in databases. It is related to two other methods:
Also read the String Methods in Python article!
Let’s now look at practical examples of using the strip() function in Python. We will explore how it works at different complexity levels. These examples will show how strip() is useful for cleaning strings in various real-life scenarios.
This example shows how the strip() function removes whitespaces and newline characters from simple strings.
line = "\n Welcome to Python! \n"
clean_line = line.strip() # Removes whitespace and newline characters
print("Before:", repr(line))
print("After:", repr(clean_line))
Output:
Before: '\n Welcome to Python! \n'
After: 'Welcome to Python!'
Explanation:
This example shows how to use strip() to remove specific characters from both ends of a string.
sentence = "!!!Learn Coding!!!"
clean_sentence = sentence.strip("!") # Removes '!' only from both ends
print("Before:", repr(sentence))
print("After:", repr(clean_sentence))
Output:
Before: '!!!Learn Coding!!!'
After: 'Learn Coding'
Explanation:
In this level, we use strip() in a loop to clean multiple values, such as those from a CSV line.
data_row = [" @Python", "Code! ", " 123 ", "\nData\n"]
cleaned_row = [item.strip(" @!\n") for item in data_row] # Clean each item
print("Original Row:", data_row)
print("Cleaned Row:", cleaned_row)
Output:
Original Row: [' @Python', 'Code! ', ' 123 ', '\nData\n']
Cleaned Row: ['Python', 'Code', '123', 'Data']
Explanation:
Here are the key situations where using strip() is helpful:
1. Cleaning User Input: When you collect user input using input(), it often includes accidental spaces or newline characters.
# Get user input with trailing spaces
username = input("Enter your name: ") # Assume user types: " Vikram "
clean_username = username.strip()
print("Before:", repr(username))
print("After:", repr(clean_username))
Output:
Before: ' Vikram '
After: 'Vikram'
Explanation:
2. Preprocessing Data from Files or APIs: When you read lines from files or external APIs, they often include trailing newline characters (\n).
# Line read from a file
line_from_file = "Data Analyst\n"
cleaned_line = line_from_file.strip()
print("Before:", repr(line_from_file))
print("After:", repr(cleaned_line))
Output:
Before: 'Data Analyst\n'
After: 'Data Analyst'
Explanation:
3. Removing Custom Padding or Symbols: Some strings may include decorative symbols or formatting characters on both ends.
text = "###Python###"
cleaned_text = text.strip("#")
print("Before:", repr(text))
print("After:", repr(cleaned_text))
Output:
Before: '###Python###'
After: 'Python'
Explanation:
Must Explore the Functions in Python article!
4. Working with Delimited Text in Lists: You can use strip() inside loops or list comprehensions to clean multiple items in one go.
# List with inconsistent formatting
raw_list = [" Data ", " Science\n", "\tML\t"]
cleaned_list = [item.strip() for item in raw_list]
print("Cleaned List:", cleaned_list)
Output:
Cleaned List: ['Data', 'Science', 'ML']
Explanation:
Using the strip in Python can make your string handling more reliable and cleaner. It works silently but effectively behind the scenes, especially in data-heavy applications.
Although the strip() in Python is simple to use, developers, especially beginners—often make mistakes when applying it. These errors can lead to unexpected results or program bugs. Let’s look at the most common ones:
The strip() function in Python is a small but powerful tool for string manipulation. It helps clean up extra spaces, unwanted characters, and newline symbols from both ends of a string. Whether you're building data pipelines, working with user input, or formatting output, using strip() can make your code cleaner and more efficient.
Yes, the strip() function supports Unicode characters. If your string contains Unicode symbols or non-ASCII characters, you can still pass them as arguments to strip() to remove them from both ends of the string.
Not directly. The strip() method is only available for string objects. However, you can apply it to a list using a loop or list comprehension. This is helpful when cleaning multiple strings at once.
If no argument is passed, strip() removes all leading and trailing whitespaces including tabs, newlines, and spaces. It does not affect characters in the middle of the string or special symbols unless specified.
Yes, the strip() function is case-sensitive. For instance, passing 'a' will remove only lowercase a and not uppercase A. To remove both, you must include both characters in the argument string.
When multiple characters are passed to strip(), it removes any combination of those characters from both ends. It does not look for the exact sequence but rather checks each character individually from the list.
strip() removes characters from the ends of a string, while split() breaks the string into a list based on a delimiter. They serve different purposes—cleaning vs separating string data.
Yes, if you pass digits (like '123') or symbols (like '$#') to strip(), it will remove those characters from the beginning and end. It won’t remove them from the middle of the string.
strip() removes characters from both ends, lstrip() removes only from the left (beginning), and rstrip() removes only from the right (end). Choose based on whether you want full, left, or right cleanup.
You can use strip() in form input validation, CSV file processing, web scraping, and chatbot message handling. It ensures that the data is cleaned before further processing or storage, reducing errors.
Individually, strip() is very lightweight and fast. But in large datasets, applying it inside heavy loops without optimization can slow things down. Vectorized methods (like using pandas .str.strip()) are better in such cases.
Absolutely. It’s common to use strip() inside if conditions to validate cleaned input. For instance, checking if a trimmed string is empty is a useful way to handle blank form submissions or data entries.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.