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,885 questions

51,811 answers

573 users

How to replace multiple characters in a string with a single character using Python

3 Answers

0 votes
def replace_multiple_characters(s, charstoreplace, replacementchar):
    for ch in charstoreplace:
        s = s.replace(ch, replacementchar)
    
    return s
   
s = "Python- #pr(o)g$ra#mming la!ng*uage"
chars = "!#$&*()-"
 
s = replace_multiple_characters(s, chars, ' ')
 
print(s)
 
 
 
'''
run:
 
Python   pr o g ra mming la ng uage
 
'''
  

 



answered Apr 15, 2021 by avibootz
edited Oct 20, 2024 by avibootz
0 votes
s = "Python- #pr(o)g$ra#mming la!ng*uage"
chars = "!#$&*()-"
 
s = s.replace('!', ' ').replace('#', ' ').replace('$', ' ').replace('&', ' ')
s = s.replace('*', ' ').replace('(', ' ').replace(')', ' ').replace('-', ' ')

print(s)
 
 
 
'''
run:
 
Python   pr o g ra mming la ng uage
 
'''

 



answered Oct 20, 2024 by avibootz
0 votes
def replace_multiple_characters(s, chars_to_replace, replacement_char):
    translation_table = str.maketrans(chars_to_replace, replacement_char * len(chars_to_replace))
    
    return s.translate(translation_table)

s = "Python- #pr(o)g$ra#mming la!ng*uage"
chars_to_replace = "!#$&*()-"
replacement_char = " "

s = replace_multiple_characters(s, chars_to_replace, replacement_char)

print(s)  

 
 
'''
run:
 
Python   pr o g ra mming la ng uage
 
'''

 



answered Oct 20, 2024 by avibootz
...