Home > OS >  How to correct the positioning of commas within a string making sure it is: "word, other word&q
How to correct the positioning of commas within a string making sure it is: "word, other word&q

Time:08-08

The comma positioning checker must make sure that the previous word is followed by a comma without leaving spaces, after the comma a space and then the other word

Example 1:

input string:

"I come with hyjk11l, hyjk11l,hyjk11l, hyjk11l,hyjk11l and hyjk11l to the center"

the output that i need:

"I come with hyjk11l, hyjk11l, hyjk11l, hyjk11l, hyjk11l and hyjk11l to the center"

Example 2:

input string:

"I run with llllkjkj   ,hyjk11l,jihjkk, hyjk11l,   ghhghgh,hjhasdjhasjd ,jashjdsa, and hyjk11l in the center"

the output that i need:

"I run with llllkjkj, hyjk11l, jihjkk, hyjk11l, ghhghgh, hjhasdjhasjd, jashjdsa, and hyjk11l in the center"

I have tried to use the replace() function in different ways but I do not get this result, I hope you can help me

CodePudding user response:

You can use re.sub:

import re

def comma(text):
    return re.sub(r"\s*,\s*", r", ", text)

print(comma("I come with hyjk11l, hyjk11l,hyjk11l, hyjk11l,hyjk11l and hyjk11l to the center"))
print(comma("I run with llllkjkj   ,hyjk11l,jihjkk, hyjk11l,   ghhghgh,hjhasdjhasjd ,jashjdsa, and hyjk11l in the center"))

# I come with hyjk11l, hyjk11l, hyjk11l, hyjk11l, hyjk11l and hyjk11l to the center
# I run with llllkjkj, hyjk11l, jihjkk, hyjk11l, ghhghgh, hjhasdjhasjd, jashjdsa, and hyjk11l in the center

The second argument does not have to be a raw-string (r"...") in this case, but I have it as a habit when it comes to re...

  • Related