How to strip (remove) punctuation from a string in Python

6 Answers

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

s = "python! :c{}@@ c++ <>@#java.*"

clean_s = ""
for char in s:
    if char not in punctuation:
        clean_s += char

print(clean_s)


'''
run:

python c c++ java

'''

 



answered Jun 17, 2017 by avibootz
edited Sep 22, 2017 by avibootz
0 votes
import re

s = "python, php. java? javascript# c@ cpp+%!@$$"

# replaces not (^) word characters or spaces with empty string
s = re.sub(r'[^\w\s]', '', s)

print(s)


'''
run:

python php java javascript c cpp

'''

 



answered Sep 22, 2017 by avibootz
edited Sep 22, 2017 by avibootz
0 votes
import string

s = "python, php. java? javascript# c@ cpp+%!@$$"

exclude = set(string.punctuation)

s = ''.join(ch for ch in s if ch not in exclude)

print(s)


'''
run:

python php java javascript c cpp

'''

 



answered Sep 22, 2017 by avibootz
edited Jul 31, 2024 by avibootz
0 votes
import string

s = "python, php. java? javascript# c@ cpp+%!@$$_"

for ch in string.punctuation:
    s = s.replace(ch, "")

print(s)


'''
run:

python php java javascript c cpp

'''

 



answered Sep 22, 2017 by avibootz
0 votes
import string

s = "python! :c{}@@ c++ <>@#java.*"

s = s.translate(str.maketrans('', '', string.punctuation))

print(s)




'''
run:

python c c java

'''

 



answered Apr 15, 2021 by avibootz
0 votes
import string
 
 
def remove_punctuation(s):
    result = ""
    for ch in s:
        if ch not in string.punctuation:
            result += ch
    return result
 
s = "#python, php!, java:, c++"
 
s = remove_punctuation(s)
 
print(s)
 
 
'''
run:
   
python php java c
 
'''

 



answered Jul 31, 2024 by avibootz

Related questions

...