For Example s = "AAA? BBB. CCC!" So, I do: import string table = str.maketrans('', '', string.punctuation) s = [w.translate(table) for w in s] And it's all right. My new sentence will be: s = "AAA BBB CCC" But, if I have input sentence like: s = "AAA? BBB. CCC! DDD.EEE" after remove punctuation the same method as below I'll have s = "AAA BBB CCC DDDEEE" but need: s = "AAA BBB CCC DDD EEE" Is any ideas/methods how to solve this problem?
I think I have a solution Code: import string def replace_punct(inp): s = '' for i in range(len(inp)): if inp[i] in string.punctuation: if inp[i+1] == ' ': s += '' else: s += ' ' else: s += inp[i] return s thestring = 'AAA? BBB. CCC! DDD.EEE' print('Input: ',thestring) print('Output: ',replace_punct(thestring)) Output: Code: ~/Documents/Python$ python3 scratch.py Input: AAA? BBB. CCC! DDD.EEE Output: AAA BBB CCC DDD EEE Hope it helps!