Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Regex that adds space after dot

Tags:

python

regex

How can I use re to write a regex in Python that finds the pattern:

dot "." followed directly by any char [a-zA-Z] (not space or digit)

and then add a space between the dot and the char?

i.e.

str="Thanks.Bob"
newsttr="Thanks. Bob"

Thanks in advance, Zvi

like image 415
Zvi Avatar asked Jun 23 '11 14:06

Zvi


People also ask

How do you put a space at the end of a string in Python?

Use the str. ljust() method to add spaces to the end of a string, e.g. result = my_str. ljust(6, ' ') . The ljust method takes the total width of the string and a fill character and pads the end of the string to the specified width with the provided fill character.

What is space in regex Python?

The space character does not have any special meaning, it just means "match a space". RE = re. compile(' +') So for your case a='rasd\nsa sd' print(re.search(' +', a))

How do you match a dot in Python?

To match a literal dot in a raw Python string ( r"" or r'' ), you need to escape it, so r"\." Unless the regular expression is stored inside a regular python string, in which case you need to use a double \ ( \\ ) instead. So, all of these are equivalent: '\\.

Is used for zero or more occurences in regex Python?

Matches zero or more repetitions of the preceding regex. For example, a* matches zero or more 'a' characters. That means it would match an empty string, 'a' , 'aa' , 'aaa' , and so on.


3 Answers

re.sub(r'\.([a-zA-Z])', r'. \1', oldstr)

like image 136
murgatroid99 Avatar answered Oct 24 '22 19:10

murgatroid99


re.sub('(?<=\.)(?=[a-zA-Z])', ' ', str)
like image 23
mhyfritz Avatar answered Oct 24 '22 19:10

mhyfritz


Try

re.sub(r"\.([a-zA-Z])", ". \\1", "Thanks.Bob")
like image 20
jena Avatar answered Oct 24 '22 21:10

jena