Python – Strip front and rear Punctuations from given String
Last Updated :
22 Apr, 2023
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
from string import punctuation
test_str = '%$Gfg is b !! est(*^&*'
print ( "The original string is : " + str (test_str))
frst_np = [idx for idx in range ( len (test_str))
if test_str[idx] not in punctuation][ 0 ]
rear_np = [idx for idx in range (
len (test_str) - 1 , - 1 , - 1 ) if test_str[idx] not in punctuation][ 0 ]
res = test_str[frst_np: rear_np + 1 ]
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
from string import punctuation
test_str = '%$Gfg is b !! est(*^&*'
print ( "The original string is : " + str (test_str))
res = ' ' .join([ele.strip(punctuation) for ele in test_str.split()])
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:
- Import the “re” module for regular expressions.
- Initialize the input string.
- Define a regular expression pattern to match punctuation marks.
- Use the re.sub() function to replace all the matches with an empty string.
- Print the original string and the modified string.
Python3
import re
import string
test_str = '%$Gfg is b !! est(*^&*'
pattern = re. compile ( '[{}]' . format (re.escape(string.punctuation)))
res = pattern.sub('', test_str)
print ( "The original string is : " + str (test_str))
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
test_str = '%$Gfg is b !! est(*^&*'
trans_table = str .maketrans(' ', ' ', punctuation)
res = test_str.translate(trans_table)
print ( "The original string is : " + str (test_str))
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
- Initialize the string:
- Define a lambda function to check if each character is a punctuation mark:
- 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:
- Convert the filtered characters back to a regular string using the join() function:
- Print the original string and the stripped string:
Python3
import string
test_str = '%$Gfg is b !! est(*^&*'
def punct_check(x): return x not in string.punctuation
filtered_str = filter (punct_check, test_str)
res = ''.join(filtered_str)
print ( "The original string is: " + str (test_str))
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():
- Import the required modules – string and reduce from the functools module.
- Initialize the input string.
- Define a lambda function to check if a character is a punctuation mark or not.
- Use the reduce() function to iterate over the characters in the input string and build a new string by adding
- each non-punctuation character to the accumulated value. The accumulated value starts as an empty string.
- Print the original input string and the filtered string.
Python3
import string
from functools import reduce
test_str = '%$Gfg is b !! est(*^&*'
def punct_check(x): return x not in string.punctuation
filtered_str = reduce ( lambda acc, x: acc +
(x if punct_check(x) else ' '), test_str, ' ')
print ( "The original string is: " + str (test_str))
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.
Similar Reads
Python - Remove Punctuation from String
In this article, we will explore various methods to Remove Punctuations from a string. Using str.translate() with str.maketrans()str.translate() method combined with is str.maketrans() one of the fastest ways to remove punctuation from a string because it works directly with string translation table
2 min read
Python | Remove the given substring from end of string
Sometimes we need to manipulate our string to remove extra information from the string for better understanding and faster processing. Given a task in which the substring needs to be removed from the end of the string using Python. Remove the substring from the end of the string using Slicing In thi
3 min read
Python - Split String on all punctuations
Given a String, Split the String on all the punctuations. Input : test_str = 'geeksforgeeks! is-best' Output : ['geeksforgeeks', '!', 'is', '-', 'best'] Explanation : Splits on '!' and '-'. Input : test_str = 'geek-sfo, rgeeks! is-best' Output : ['geek', '-', 'sfo', ', ', 'rgeeks', '!', 'is', '-', '
3 min read
Python - Remove front K characters from each string in String List
Sometimes, we come across an issue in which we require to delete the first K characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a
6 min read
Python - Reverse String except punctuations
Given a string with punctuations, perform string reverse, leaving punctuations at their places. Input : test_str = 'geeks@#for&%%gee)ks' Output : skeeg@#rof&%%ske)eg Explanation : Whole string is reversed, except the punctuations. Input : test_str = 'geeks@#for&%%gee)ks' [ only substring
6 min read
Python - Triple quote String concatenation
Sometimes, while working with Python Strings, we can have a problem in which we need to perform concatenation of Strings which are constructed by Triple quotes. This happens in cases we have multiline strings. This can have applications in many domains. Let us discuss certain ways in which this task
4 min read
Python | Remove given character from Strings list
Sometimes, while working with Python list, we can have a problem in which we need to remove a particular character from each string from list. This kind of application can come in many domains. Let's discuss certain ways to solve this problem. Method #1 : Using replace() + enumerate() + loop This is
8 min read
Python | Ways to remove numeric digits from given string
In Python, we can remove numeric digits from a string in multiple ways. For example, if we have a string like "Geeks123" and we want to remove the numbers to get "Geeks", we can use different methods to accomplish this. We can do this by using techniques such as list comprehension, regular expressio
3 min read
Python | Get the string after occurrence of given substring
The problem involves getting the string that is occurring after the substring has been found. Let's discuss certain ways in which this task can be performed using Python. Using partition()To extract the portion of a string that occurs after a specific substring partition() method is an efficient and
3 min read
Replace a String character at given index in Python
In Python, strings are immutable, meaning they cannot be directly modified. We need to create a new string using various methods to replace a character at a specific index. Using slicingSlicing is one of the most efficient ways to replace a character at a specific index. [GFGTABS] Python s = "h
2 min read