How to replace punctuation with a letter in a string with Python

2 Answers

0 votes
import re
 
def replace_punctuation(string, ch):
    return re.sub(r"[^\w\s]", " ", string)
    
# \w = letters, digits, underscore
# \s = whitespace
# [^...] = “anything not in this set” → punctuation    
     
string = "In my opinion, we ;need * to keep? write code and use AI. "
 
string = replace_punctuation(string, ' ')
 
print(string)
 
 
 
'''
run:
 
In my opinion  we  need   to keep  write code and use AI  
 
'''

 



answered Feb 14 by avibootz
edited Feb 14 by avibootz
0 votes
import string

# string.punctuation includes: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

def replace_punctuation(text, letter):
    return "".join(letter if ch in string.punctuation else ch for ch in text)
    
text = "In my opinion, we ;need * to keep? write code and use AI. "

text = replace_punctuation(text, ' ')

print(text)



'''
run:

In my opinion  we  need   to keep  write code and use AI  

'''

 



answered Feb 14 by avibootz
...