Open In App

Python – Strip front and rear Punctuations from given String

Last Updated : 22 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string strip rear and front punctuations. 

Input : test_str = ‘%$Gfg is b!!est(*^’ 

Output : Gfg is b!!est 

Explanation : Front and rear punctuations are stripped. 

Input : test_str = ‘%Gfg is b!!est(*^’ 

Output : Gfg is b!!est 

Explanation : Front and rear punctuations are stripped.

Method #1 : Using punctuation() + loop

In this, we use punctuation() to check for punctuations, from both rear and front, once, non-pnc char is found, index is recorded and string is splitted.

Python3




# Python3 code to demonstrate working of
# Strip Punctuations from String
# Using loop + punctuation
from string import punctuation
 
# initializing string
test_str = '%$Gfg is b !! est(*^&*'
 
# printing original string
print("The original string is : " + str(test_str))
 
# getting first non-pnc idx
frst_np = [idx for idx in range(len(test_str))
           if test_str[idx] not in punctuation][0]
 
# getting rear non-pnc idx
rear_np = [idx for idx in range(
    len(test_str) - 1, -1, -1) if test_str[idx] not in punctuation][0]
 
# spittd string
res = test_str[frst_np: rear_np + 1]
 
# printing result
print("The stripped string : " + str(res))


Output

The original string is : %$Gfg is b!!est(*^&*
The stripped string : Gfg is b!!est

The time complexity of this program is O(N), where N is the length of the input string test_str. 

The space complexity of this program is also O(N), since it creates two lists to store the indices of the non-punctuation characters. 

Method #2 : Using strip() + split() + join()

In this, we perform task of splitting using split(), to get individual words, strip() is used to remove punctuations. Lastly join() is used to perform joining of words.

Python3




# Python3 code to demonstrate working of
# Strip Punctuations from String
# Using strip() + split() + join()
from string import punctuation
 
# initializing string
test_str = '%$Gfg is b !! est(*^&*'
 
# printing original string
print("The original string is : " + str(test_str))
 
# strip is used to remove rear punctuations
res = ' '.join([ele.strip(punctuation) for ele in test_str.split()])
 
# printing result
print("The stripped string : " + str(res))


Output

The original string is : %$Gfg is b!!est(*^&*
The stripped string : Gfg is b!!est

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #4: Using Regular Expressions

Approach:

  1. Import the “re” module for regular expressions.
  2. Initialize the input string.
  3. Define a regular expression pattern to match punctuation marks.
  4. Use the re.sub() function to replace all the matches with an empty string.
  5. Print the original string and the modified string.

Python3




import re
import string
 
# initializing string
test_str = '%$Gfg is b !! est(*^&*'
 
# defining pattern to match punctuation marks
pattern = re.compile('[{}]'.format(re.escape(string.punctuation)))
 
# using sub() function to replace matches with empty string
res = pattern.sub('', test_str)
 
# printing original string
print("The original string is : " + str(test_str))
 
# printing result
print("The stripped string : " + str(res))


Output

The original string is : %$Gfg is b !! est(*^&*
The stripped string : Gfg is b  est

Time Complexity: The time complexity of this method is O(n), where n is the length of the input string.
Auxiliary Space: The auxiliary space complexity of this method is O(n), where n is the length of the input string.

Method #4: Using translate() method

The translate() method is a built-in Python method that can be used to replace/remove characters from a string. We can create a translation table using the maketrans() method of the string module, which can then be used to remove the punctuation from the string.

Step 1: Initialize the string
Step 2: Create a translation table using the maketrans() method of the string module

Step 3: Use the translate() method to remove the punctuation from the string
Step 4: Print the result

Python3




from string import punctuation
 
# initializing string
test_str = '%$Gfg is b !! est(*^&*'
 
# creating a translation table using the maketrans() method
trans_table = str.maketrans('', '', punctuation)
 
# using the translate() method to remove the punctuation from the string
res = test_str.translate(trans_table)
 
# printing the original string
print("The original string is : " + str(test_str))
 
# printing the stripped string
print("The stripped string : " + str(res))


Output

The original string is : %$Gfg is b !! est(*^&*
The stripped string : Gfg is b  est

Time complexity: O(n)
Auxiliary space: O(n)

Method 5 : using the filter() and lambda functions

  1. Initialize the string:
  2. Define a lambda function to check if each character is a punctuation mark:
  3. Use the filter() function to remove punctuation marks from the string. The first argument of filter() should be the lambda function defined in step 2, and the second argument should be the string to filter:
  4. Convert the filtered characters back to a regular string using the join() function:
  5. Print the original string and the stripped string:

Python3




import string
 
# initializing string
test_str = '%$Gfg is b !! est(*^&*'
 
# defining lambda function to filter out punctuation marks
 
 
def punct_check(x): return x not in string.punctuation
 
 
# using filter() function to remove punctuation marks
filtered_str = filter(punct_check, test_str)
 
# converting filtered characters back to string using join()
res = ''.join(filtered_str)
 
# printing original string
print("The original string is: " + str(test_str))
 
# printing result
print("The stripped string: " + str(res))


Output

The original string is: %$Gfg is b !! est(*^&*
The stripped string: Gfg is b  est

Time complexity: O(n), where n is the length of the input string.

Auxiliary space: O(n), as a new string needs to be created to store the filtered characters.

Method 6: using reduce():

  1. Import the required modules – string and reduce from the functools module.
  2. Initialize the input string.
  3. Define a lambda function to check if a character is a punctuation mark or not.
  4. Use the reduce() function to iterate over the characters in the input string and build a new string by adding
  5. each non-punctuation character to the accumulated value. The accumulated value starts as an empty string.
  6. Print the original input string and the filtered string.

Python3




import string
from functools import reduce
 
# initializing string
test_str = '%$Gfg is b !! est(*^&*'
 
# defining lambda function to filter
# out punctuation marks
def punct_check(x): return x not in string.punctuation
 
# using reduce() function to remove
# the punctuation marks
filtered_str = reduce(lambda acc, x: acc +
                      (x if punct_check(x) else ''), test_str, '')
 
# Print the original string
print("The original string is: " + str(test_str))
 
# Print the result
print("The stripped string: " + str(filtered_str))


Output

The original string is: %$Gfg is b !! est(*^&*
The stripped string: Gfg is b  est

Time Complexity: O(n), where n is the length of the input string. This is because we need to iterate over each character in the input string to filter out the punctuation marks.

Space Complexity: O(n), where n is the length of the input string. This is because we need to store the filtered string in memory, which can be up to the same length as the input string if no characters are filtered out.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads