TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python String Strip Tutorial
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python String Strip Tutorial

Last updated: Jan 21, 2024 6:45 pm
By Harsh S.
Share
7 Min Read
Python String Strip Basics
SHARE

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.

Contents
Basic Usage of Python String Strip()Stripping Specific Characterslstrip() and rstrip() MethodsUnderstand How Strip Works with ExamplesRemoving Whitespace from User InputProcessing a List of File PathsStripping Specific Characters from a URLComparison of String Stripping Methods

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.

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

Conclusion

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!

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Harsh S. Avatar
By Harsh S.
Follow:
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 projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Class Definitions in Python Class Definitions in Python
Next Article Simple Android Data Analytics App in Python Simple Android Data Analytics App in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x