简体   繁体   中英

How to replace punctuation with space python

I use this code for removing punctuation from sentence but Now I need to replace the punctuation with space

sentence = 'hi,how are you?'
temp = ''.join([''.join(c for c in s if c not in string.punctuation) for s in sentence])

outPut => `hihow are you`

I need to be like this

outPut => `hi how are you`

I need the fastest way to do that

You can tweak your generator comprehension, by using conditional expression :

import string

sentence = 'hi,how are you?'
temp = ''.join(c if c not in string.punctuation else ' ' for c in sentence)
print(temp) # hi how are you

You could use a regex approach here:

import string
import re

sentence = 'hi,how are you?'
output = re.sub(r'[' + string.punctuation + r']+', ' ', sentence).strip()
print(output)  # hi how are you

Python has a built-in function for replacing.

sentence = 'The.quick.brown.fox.jumps.over.the.lazy.dog'

print(sentence.replace('.',' '))

You can use the method sub in package re to do a sweeping substitution:

import string 

re.sub(f'[{string.punctuation}]+', " ", s)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM