Algorithm
-
Input:
- Accept the input string that needs whitespace trimming.
-
Initialize Variables:
- Initialize two pointers,
start
andend
, to track the range of characters in the string.
- Initialize two pointers,
-
Trim Leading Whitespace:
- Iterate through the string from the beginning.
- Move the
start
pointer until a non-whitespace character is encountered.
-
Trim Trailing Whitespace:
- Iterate through the string from the end.
- Move the
end
pointer until a non-whitespace character is encountered.
-
Extract Substring:
- Extract the substring from the original string using the
start
andend
pointers.
- Extract the substring from the original string using the
-
Output:
- Return the trimmed substring.
Code Examples
#1 Code Example- Using strip()
Code -
Python Programming
my_string = " Python "
print(my_string.strip())
Copy The Code &
Try With Live Editor
Output
Python
#2 Code Example with Python Programming
Code -
Python Programming
my_string = " \nPython "
print(my_string.strip(" "))
Copy The Code &
Try With Live Editor
Output
Python
#3 Code Example- Using regular expression
Code -
Python Programming
import re
my_string = " Hello Python "
output = re.sub(r'^\s+|\s+$', '', my_string)
print(output)
Copy The Code &
Try With Live Editor
Output
Hello python
Demonstration
Python Programing Example to Trim Whitespace From a String-DevsEnv