Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to trim a string from both sides
Python provides several built-in methods to trim or remove characters from both sides of a string. The term "trim" means to remove unwanted characters from the beginning and end of a string.
For example ?
Given string is 'iiiiiiiiiiiBOXERiiiiiiiiii' and we want to remove the character 'i' from both sides. The final result becomes BOXER.
Methods for Trimming Strings
Using strip() Method
The strip() method removes whitespace or specified characters from both ends of a string ?
s_trim = " APPLE "
trim_str = s_trim.strip()
print("Trim the whitespace from both left and right sides:", trim_str)
Trim the whitespace from both left and right sides: APPLE
Using String Slicing with While Loop
You can use string slicing with a loop to remove specific characters from both ends ?
bs_trim = "aaaaPetersonaaaa"
# Remove 'a' from both ends using while loop
while bs_trim and bs_trim[0] == "a":
bs_trim = bs_trim[1:] # trim from left side
while bs_trim and bs_trim[-1] == "a":
bs_trim = bs_trim[:-1] # trim from right side
print("After trimming the character 'a' from both sides:", bs_trim)
After trimming the character 'a' from both sides: Peterson
Using lstrip() and rstrip() Together
Combine lstrip() (left strip) and rstrip() (right strip) to remove different characters from each side ?
lr_trim = "k5ktgreSawanKumar543"
trim_str = lr_trim.lstrip('k5ktgre').rstrip('543')
print("After trimming different characters from both sides:", trim_str)
After trimming different characters from both sides: SawanKumar
Using replace() Method
The replace() method removes all occurrences of a character throughout the string ?
lr_trim = "iiiiiiiiiiiBOXERiiiiiiiiii"
trim_str = lr_trim.replace("i", "")
print("After removing all 'i' characters:", trim_str)
After removing all 'i' characters: BOXER
Comparison of Methods
| Method | Removes From | Best For |
|---|---|---|
strip() |
Both ends only | Whitespace or specific characters from edges |
lstrip() + rstrip() |
Left and right separately | Different characters from each side |
| String slicing | Both ends with logic | Custom trimming conditions |
replace() |
Entire string | Removing all occurrences of a character |
Conclusion
Use strip() for removing whitespace or characters from both ends. For different characters on each side, combine lstrip() and rstrip(). The replace() method removes characters throughout the entire string.
