Algorithm


  1. Input:

    • Accept the input string that needs whitespace trimming.
  2. Initialize Variables:

    • Initialize two pointers, start and end, to track the range of characters in the string.
  3. Trim Leading Whitespace:

    • Iterate through the string from the beginning.
    • Move the start pointer until a non-whitespace character is encountered.
  4. Trim Trailing Whitespace:

    • Iterate through the string from the end.
    • Move the end pointer until a non-whitespace character is encountered.
  5. Extract Substring:

    • Extract the substring from the original string using the start and end pointers.
  6. 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

x
+
cmd
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

x
+
cmd
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

x
+
cmd
Hello python
Advertisements

Demonstration


Python Programing Example to Trim Whitespace From a String-DevsEnv