Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

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 12 hours ago by avibootz
edited 12 hours ago 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 12 hours ago by avibootz
...