Python String Strip()

Harsh S.
By
Harsh S.
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale...
7 Min Read

In Python, the strip() method is used to remove start and finish whitespace characters (spaces, tabs, and newline characters) from a string. This can be incredibly useful when working with user input, file parsing, or any other situation where you need to clean up text data. This tutorial will walk you through the usage of the strip() method, along with other related methods and techniques.

What is strip() in Python?

The strip() method is a built-in Python string method that returns a new string with start and finish whitespace removed. The original string is not modified; instead, a new string is created with the desired changes. The general syntax of the strip() method is as follows:

str_no_whitespace = str_with_whitespaces.strip()

Where:

  • str_with_whitespaces is the string you want to remove whitespace from.
  • str_no_whitespace is the resulting string with start and finish whitespace removed.

Also Read: How to Split Strings in Python

Basic Usage of Python String Strip()

The strip() method comes to the task in a variety of situations, such as:

  • Cleaning up user input
  • Normalizing data
  • Preparing data for parsing
  • Formatting text for display

Let’s start with some basic examples to understand how strip() works:

orig_str = "  What's up, Python?  "
post_strip = orig_str.strip()
print(post_strip)

Output:

What's up, Python?

In the above code, the strip() method removed the spaces from the front and rear part of the orig_str variable, resulting in a clean string.

Related Topic – How to Remove Characters from a String in Python

Stripping Specific Characters

By default, the Python strip() removes all start and finish whitespace characters from a string. However, you can also specify the characters you want to remove by passing them as parameters to the strip() method. For example:

orig_str = "**What's up, Python?**"
post_strip = orig_str.strip('*')
print(post_strip)

Output:

What's up, Python?

In this case, we specified the asterisk character ‘*’ as the argument to strip(), and it removed the asterisks from both ends of the string.

Also Check: How to Reverse a String in Python

lstrip() and rstrip() Methods

If you need to remove whitespace only from one end of the string (left or right), Python provides two other methods: lstrip() and rstrip(). You can take these two functions as a supplement to the Python string strip method.

  • lstrip(): Removes leading whitespace characters.
  • rstrip(): Removes trailing whitespace characters.

Here are examples of how to use these methods:

orig_str = "  Left whitespace   "
left_strip = orig_str.lstrip()
right_strip = orig_str.rstrip()

print(left_strip)
print(right_strip)

Output:

Left whitespace   
  Left whitespace

In the first case, lstrip() removed the leading whitespace, and in the second case, rstrip() removed the trailing whitespace.

Understand How Strip Works with Examples

Let’s explore some more examples to see how strip(), lstrip(), and rstrip() methods can be used in the real world to strip whitespaces from strings in Python.

Must Check: Python multiline string Interpolation

Note: String interpolation is like inserting placeholders in a sentence that can be filled with values when the sentence is used.

Removing Whitespace from User Input

user_in = input("Enter a string: ")
clear_in_str = user_in.strip()
print("Cleaned input:", clear_in_str)

This code takes a user’s input, removes any leading or trailing whitespace, and then displays the cleaned input.

Processing a List of File Paths

Suppose you have a list of file paths, and some of them contain extra spaces:

file_paths = [" path/to/file.txt  ", "  another/path/to/file2.txt"]
cleaned_paths = [path.strip() for path in file_paths]
print("Cleaned file paths:", cleaned_paths)

This code cleans up file paths in a list by removing start and finish spaces from each path.

Stripping Specific Characters from a URL

You can use strip() to clean up URLs by removing unwanted characters:

url = "https://www.example.com/***"
clean_url = url.strip('*')
print("Cleaned URL:", clean_url)

This code removes asterisks from both ends of a URL, leaving a clean and valid URL.

Also Check: Python Ord() Function All You Need to Know

Comparison of String Stripping Methods

Here’s a table comparing the different string-stripping methods:

MethodDescriptionExample
strip()Removes start and finish whitespace"What's up, Python? ".strip()
strip(char)Removes specified character from ends"**What's up, Python?**".strip('*')
lstrip()Removes opening whitespace" Left whitespace ".lstrip()
rstrip()Removes closing whitespace" Left whitespace ".rstrip()
Comparison of Python String Strip Functions

Recommendation: Use strip() when you need to remove both opening and closing whitespace. If you need to remove whitespace from only one end, use lstrip() or rstrip(). When you need to remove specific characters, pass the character as a parameter to strip().

Must Read: How to Iterate Strings in Python

Before You Leave

The strip(), lstrip(), and rstrip() methods are essential tools for cleaning up strings in Python. They allow you to easily remove unwanted whitespace and characters from text data, making your code more robust and user-friendly. By understanding these methods and their applications, you can handle text manipulation tasks effectively and produce cleaner, more reliable code.

Remember to choose the appropriate method based on your specific requirements. If you need to remove both beginning and ending whitespaces, use strip(). If you need to remove whitespace from one end, use lstrip() or rstrip. And if you need to remove specific characters, pass the character as a parameter to strip().

Now that you have a good understanding of Python’s string-stripping methods, you can start using them in your projects to work with text data more efficiently.

Happy Coding,
TechBeamers.

Share This Article
Leave a Comment
Subscribe
Notify of
guest


0 Comments
Newest
Oldest
Inline Feedbacks
View all comments