Python | Replace punctuations with K
Last Updated :
11 May, 2023
Sometimes, while working with Python Strings, we have a problem in which we need to perform the replacement of punctuations in String with specific characters. This can have applications in many domains such as day-day programming. Let’s discuss certain ways in which this task can be performed.
Method #1: Using string.punctuation + replace() The combination of the above functions can be used to solve this problem. In this, we extract all punctuations using punctuation and perform a replacement of the character desired using replace().
Python3
from string import punctuation
test_str = 'geeksforgeeks, is : best for ; geeks !!'
print ( "The original string is : " + str (test_str))
repl_char = '*'
for chr in punctuation:
test_str = test_str.replace( chr , repl_char)
print ( "The strings after replacement : " + test_str)
|
Output :
The original string is : geeksforgeeks, is : best for ; geeks!!
The strings after replacement : geeksforgeeks* is * best for * geeks**
Method #2: Using regex This problem can be solved using regex. In this, we employ a regex to substitute for all punctuations.
Python3
import re
test_str = 'geeksforgeeks, is : best for ; geeks !!'
print ( "The original string is : " + str (test_str))
repl_char = '*'
res = re.sub(r '[^\w\s]' , repl_char, test_str)
print ( "The strings after replacement : " + res)
|
Output :
The original string is : geeksforgeeks, is : best for ; geeks!!
The strings after replacement : geeksforgeeks* is * best for * geeks**
Time Complexity: O(N)
Space Complexity: O(N)
Method #3: Using translate() method replace punctuations with K:
- Initialize the input string “est_str.
- Initialize the replace character repl_char.
- Create a translator using str.maketrans() method with two arguments the first argument is string.punctuation(), which is the list of all punctuations in the string module and The second argument is the “*” character multiplied by the length of the first argument, which will be the replacement character.
- Use the translate() method to replace all the punctuation with the replacement character.
- Store the translated string in “test_str” and print the string after replacement.
Below is the implementation of the above approach:
Python3
import string
test_str = 'geeksforgeeks, is : best for ; geeks !!'
print ( "The original string is : " + str (test_str))
repl_char = '*'
translator = str .maketrans(
string.punctuation, repl_char * len (string.punctuation))
test_str = test_str.translate(translator)
print ( "The strings after replacement : " + test_str)
|
Output
The original string is : geeksforgeeks, is : best for ; geeks !!
The strings after replacement : geeksforgeeks* is * best for * geeks **
Time Complexity: O(N)
Space Complexity: O(N)
Method #4: using the join() method:
- The string test_str is initialized
- The replace character repl_char is initialized
- The string of all possible punctuation marks is initialized using the punctuation module of the string library.
- The join() method is used to replace each punctuation mark in the string test_str with the replacement character.
- The join() method is used in combination with a ternary operator which checks if each character in test_str is a punctuation mark or not.
- If it is a punctuation mark, then the replacement character is used, otherwise the original character is used. The result of this operation is a string with all the punctuation marks replaced with the replacement character.
- The resulting string is printed using print() function.
Python3
test_str = 'geeksforgeeks, is : best for ; geeks !!'
print ( "The original string is : " + str (test_str))
repl_char = '*'
punctuations =
res = ''.join(repl_char if char in punctuations else char for char in test_str)
print ( "The string after replacement : " + res)
|
Output
The original string is : geeksforgeeks, is : best for ; geeks !!
The string after replacement : geeksforgeeks* is * best for * geeks **
The time complexity of this approach is O(n), where n is the length of the input string.
The space complexity of this approach is O(n), where n is the length of the input string
Method 5: Using a loop to iterate through each character in the string and checking if it is a punctuation character.
Step-by-step approach
- Initialize the replace character repl_char to ‘*’.
- Initialize the string of punctuation characters punctuations to ”’!()-[]{};:'”,<>./?@#$%^&*_~”’.
- Initialize an empty string res to store the modified string.
- Use a loop to iterate through each character in the input string test_str.
- Check if the current character is a punctuation character by using the in operator to check if it exists in the punctuations string.
- If the current character is a punctuation character, then append the repl_char to the res string.
- If the current character is not a punctuation character, then append the current character to the res string.
- After iterating through all the characters in the input string, print the modified string using the print() function.
Python3
test_str = 'geeksforgeeks, is : best for ; geeks !!'
print ( "The original string is : " + str (test_str))
repl_char = '*'
punctuations =
res = ''
for char in test_str:
if char in punctuations:
res + = repl_char
else :
res + = char
print ( "The string after replacement : " + res)
|
Output
The original string is : geeksforgeeks, is : best for ; geeks !!
The string after replacement : geeksforgeeks* is * best for * geeks **
Time complexity: O(n) where n is the length of the input string since we iterate through each character in the string once.
Auxiliary space: O(n) since we use a new string to store the modified string which can be of the same length as the input string if all characters are punctuation characters.
Method 6: Using recursive implementation:
- Define a string test_str.
- Initialize the replace character repl_char to *.
- Define a string of punctuations punctuations.
- Initialize an empty string res.
- Iterate over each character in the test_str.
- If the character is a punctuation mark, append repl_char to res, otherwise append the character to res.
- Print the original string and the modified string.
Python3
def replace_punctuations(string, repl_char):
punctuations =
if len (string) = = 0 :
return ''
elif string[ 0 ] in punctuations:
return repl_char + replace_punctuations(string[ 1 :], repl_char)
else :
return string[ 0 ] + replace_punctuations(string[ 1 :], repl_char)
test_str = 'geeksforgeeks, is : best for ; geeks !!'
repl_char = '*'
print ( "The original string is : " + str (test_str))
res = replace_punctuations(test_str, repl_char)
print ( "The string after replacement : " + res)
|
Output
The original string is : geeksforgeeks, is : best for ; geeks !!
The string after replacement : geeksforgeeks* is * best for * geeks **
The time complexity: O(n), where n is the length of the input string test_str. This is because we iterate over each character in the string exactly once, and the time taken to perform the other operations is constant.
The space complexity: O(n), because we are creating a new string res of the same length as the input string to store the modified string.
Similar Reads
Python - Replace Non-None with K
Sometimes, while working with Python lists we can have a problem in which we need to perform the replacement of all the elements that are non-None. This kind of problem can have applications in many domains such as web development and day-day programming. Let's discuss certain ways in which this tas
6 min read
Python - Remove Punctuation Tuples
Sometimes, while working with Python tuples, we can have a problem in which we need to perform the removal of all the tuples which contain punctuation in tuples. This kind of problem can occur in data filtering applications. Let's discuss certain ways in which this task can be performed. Input : tes
8 min read
Replace multiple words with K - Python
We are given a string s and the task is to replace all occurrences of specified target words with a single replacement word K.For example, given text = "apple orange banana" and words_to_replace = ["apple", "banana"], the output will be "K orange K". Using List ComprehensionThis is the most efficien
4 min read
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 - Replace K with Multiple values
Sometimes, while working with Python Strings, we can have a problem in which we need to perform replace of single character/work with particular list of values, based on occurrence. This kind of problem can have application in school and day-day programming. Let's discuss certain ways in which this
5 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 - 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 - Replace words from Dictionary
Replacing words in a string using a dictionary allows us to efficiently map specific words to new values. Using str.replace() in a LoopUsing str.replace() in a loop, you can systematically replace specific substrings within a string with new values. This approach is useful for repetitive replacement
3 min read
re.split() in Python
The re.split() method in Python is used to split a string by a pattern (using regular expressions). It is part of the re-module, which provides support for working with regular expressions. This method is helpful when we need to split a string into multiple parts based on complex patterns rather tha
3 min read
Python - Replace multiple characters at once
Replacing multiple characters in a string is a common task in Python Below, we explore methods to replace multiple characters at once, ranked from the most efficient to the least. Using translate() with maketrans() translate() method combined with maketrans() is the most efficient way to replace mul
2 min read