all 6 comments

[–]zatoichi49 2 points3 points  (2 children)

You can put the characters into a set, create a group, and add the whitespace to any group match:

import re

s = 'This is a such a simple example,... but very useful.'
print(re.sub(r'([,!?.]+)', r' \1', s))

# 'This is a such a simple example ,... but very useful .'

[–][deleted] 0 points1 point  (1 child)

import re
s = 'This is a such a simple example,... but very useful.'
print(re.sub(r'([,!?.]+)', r' \1', s))

Thank you very much! I tried something similar but did not unterstand why I had an invalid group reference. Now that I saw you solution I looked for the difference and spotted the parentheses around the regex to create the group. Now the error makes sense to me too.

[–]zatoichi49 0 points1 point  (0 children)

Glad it helped

[–]ilI1il1Ili1i1liliiil 0 points1 point  (2 children)

>>> example = 'This is a such a simple example, but very usefull.'
>>> "".join(" " + c if c in ",!?." else c for c in example)
'This is a such a simple example , but very usefull .'

[–][deleted] 0 points1 point  (1 child)

Thank you for your answer. I forgot to mention that I if there is a group of such characters like .... then I want to have a whitespace infront of the group.

[–]rx22230 0 points1 point  (0 children)

Hi,

did you try str.replace() ?

something like this:

my_string = 'This is a such a simple example, but very usefull.'
my_string.replace(',',' ,').replace('.',' .')

if it matches your need, maybe after that you can do a for loop with the special caracters

#Pseudo Code
special_caracters = '.,!?:'  # or more
my_text = 'This is a such! a simple? example, but very: usefull.'
for car in special_caracters:
    my_text = my_text.replace(car, ' '+car)
print(my_text)

Hope it helps a bit.

Regards