EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials Python String Tutorial Python Trim String
 

Python Trim String

Lalita Gupta
Article byLalita Gupta
EDUCBA
Reviewed byRavi Rathore

Python Trim String

Introduction to Python Trim String

String is a sequence of characters. The character can be any letter, digit, whitespace character or any special symbols. Strings in Python are immutable, which means once created, it cannot be modified. However, we can make a copy of the string and can perform various operations on it. For this, Python provides a separate class “str” for string handling and manipulations. One such operation is to remove whitespace characters from the start and/or end of the string called Trim. We can remove whitespace character using loops, but Python provides a built-in function to make this task easier.

 

 

Python provides three different Trim functions:

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

different Trim functions

  • strip()
  • rstrip()
  • lstrip()

Syntax:

1. strip(): strip() function returns a copy of the string after removing spaces from both left and right of the string, i.e. both leading and trailing whitespaces are removed.

string_object.strip([chars])

2. lstrip(): lstrip() function returns a copy of the string after removing leading whitespaces, which means from the left of the string.

string_object.lstrip([chars])

3. rstrip(): rstrip() function returns a copy of the string after removing trailing whitespaces, which means from the right of the string.

string_object.rstrip([chars])

In all the three syntaxes mentioned above, [char] is an optional parameter. If it is not provided, then by default, whitespace characters (spaces, tabs, newline chars) are removed. But if an optional parameter [char] is provided in the function, then matching characters will be removed from the string.

Why Trim String is used in Python?

  • We do not always get clean data as data is collected from disparate sources.
  •  Data is often noisy, and String Trim is one of the ways to clean the data so that it can be manipulated efficiently.

Examples of Python Trim String

Given below are the examples of Python Trim String:

Example #1

Python program to illustrate strip() functionality.

Code:

# Traditional way to remove whitespaces from the given string
print("-------------- Method 1 : using loops-------------->")
string = '   Python     '
print("length of input string :", string, '-->', len(string))
# output string
out_str1 = ""
# for loop to remove whitespaces
for i in string:
    if i==' ':
        pass
    else :
        out_str1 += i
print("output string 1 :(", out_str1, ")is of", len(out_str1), "characters")
print('\n')
print("-------------- Method 2 : using replace()-------------->")
def remove_spaces(s):
    return s.replace(' ' , '')
out_str2 = remove_spaces(string)
print("output string 2 :(", out_str2, ")is of", len(out_str2), "characters" )
print('\n')
# removing whitesspaces using built-in function
print("-------------- Method 3 : using strip()-------------->")
out_str3 = string.strip()
print("output string 3 :(", out_str3, ")is of", len(out_str3), "characters" )

Output:

python trim string 1

Explanation:

In this example, three ways are used to remove white spaces from the input string “python”.

  • Using for loop: Length of the input string is printed, which includes spaces as well. The input string is then traversed using for loop. For each character, if space ‘ ‘ is found, we pass a null statement, i.e. on the encounter of a space, nothing will happen. But if the character is not in space, then it will be concatenated to output string “out_str1”.Finally, the length of out string is printed.
  • Using string built-in function replace(): Here, we have defined a function which will take a string as its argument and return a copy of this string replacing a space ‘ ‘ with a null string using built-in function replace()
  • Using strip() function: Last but not the least strip() function is used. It is called on the input string without any parameters. So by default, both leading and trailing spaces are removed.

Example #2

Python program to illustrate the working of lstrip() and rstrip() functions.

Code:

string = " Python trim functions    "
print("Input string(", string, ") is of", len(string), "characters")
# lsrtip() removes leading spaces
print('\n')
print("Illustartion of lsrip()")
ostring1 = string.lstrip()
print("output string 1:", ostring1)
print("'", ostring1, "'", "length :", len(ostring1))
print('\n')
# rstrip() removes trailing spaces
print("Illustartion of rsrip()")
ostring2 = string.rstrip()
print("output string 2:", ostring2)
print("'", ostring2, "'", "length :", len(ostring2))

Output:

python trim string 2

Explanation:

  • In the above example, lstrip() and rstrip() functions are called on input string without specifying any optional parameters. So by default, spaces will be removed.
  • The total length (number of chars) of the original string and trimmed strings are printed.

Example #3

Illustration of strip([chars]), lstrip([char]) and rstrip([char]) when optional parameter [char] is specified

Code:

# strip([chars]), lstrip([char]) and rstrip([char]) when optiona parameter [char] is specified
string = '********Python Trim String**********'
print('Input String', string)
print('length :', len(string), 'chars')
print('\n')
print("strip()--> * will be removed from both ends")
str1 = string.strip('*')
print(str1)
print('length :', len(str1), 'chars')
print('\n')
print("lstrip()--> leading * from the string will be removed")
str2 = string.lstrip('*')
print(str2)
print('length :', len(str2), 'chars')
print('\n')
print("rstrip()--> trailing * from the string will be removed")
str3 = string.rstrip('*')
print(str3)
print('length :', len(str3), 'chars')

Output:

python trim string 3

Explanation:

  • In the above example, all three trimmed functions strip(), lstrip() and rstrip() takes an optional parameter ‘*’.strip(*) removes both leading and trailing ‘*’ from the given input string.
  • While lstrip() and rstrip() have removed leading and trailing ‘*’ respectively.
  • The length of the input string and trimmed strings are then printed.

Example #4

Extracting sub domain name from a given list of URls using strip() function

Code:

# Program to extract sub domain name from a list of URLs using strip() function
# Input list containing different URLs
urls = ['www.facebook.com', 'www.yatra.com', 'www.youtube.com']
print("sub domains:")
for url in urls:
    print(url.strip('w.com'))

Output:

output

Explanation:

  • Input list containing different URLs is defined
  • for loop is used to traverse the list. On each list item, i.e. a url, strip() is called, which will remove ‘www.’ and ‘.com’ a part from the urls as shown above.

Conclusion

String trim is useful for cleaning of data as data is collected from different sources and is always noisy and messy. strip(), lstrip() and rstrip() are the three built-in functions provided by the Python “str” class which helps in string trimming. Though this can be achieved using various traditional ways, these functions make this task a lot easier.

Recommended Articles

We hope that this EDUCBA information on “Python Trim String” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. Python String Operations
  2. Python List Functions
  3. Python Input String
  4. Queue in Python

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW