×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python String strip() Method

By IncludeHelp Last updated : December 08, 2024

Python String strip() Method

The strip() is an in-built function in Python and it is used to remove leading and trailing spaces from a string, strip() is called with the string object (variable), does not take any argument generally (one argument is optional which we will discuss in next article) and it returns a copy of string without leading and trailing spaces.

Syntax

string.strip()

Note: There is an optional parameter, which is used to remove particular character/string from the beginning and end of the string.

Sample Input/Output

Input string: "    Hello world    "
Output string: "Hello world"

Example 1

Python code to remove leading and trailing spaces from a string (An example of string.strip() function)

# Python code to remove leading & trailing spaces
# An example of the string.strip() function

# Defining the string
str_var = "    Hello world   "

# Printing the actual string
print("Actual string is:\n", str_var)

# Printing the string without leading & trailing spaces
print("String w/o spaces is:\n", str_var.strip())

Output

Actual string is:
    Hello world   
String w/o spaces is:
Hello world

It does not remove spaces between the words

Example 2

In this example, there were spaces before the string and between the words, but function will remove only spaces before the string (Leading spaces), it will not remove spaces between the words. Consider the given example,

# Python code to remove leading & trailing spaces
# An example of the string.strip() function

# Defining the string
str_var = "    Hello     world   "

# Printing the actual string
print("Actual string is:\n", str_var)

# Printing the string without leading & trailing spaces
print("String w/o spaces is:\n", str_var.strip())

Output

Actual string is:
    Hello     world
String w/o spaces is:
Hello     world

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.