2

I have a string with multiple commas and spaces as delimiters between words. Here are some examples:

ex #1: string = 'word1,,,,,,,     word2,,,,,,     word3,,,,,,'  
ex #2: string = 'word1         word2       word3'  
ex #3: string = 'word1,word2,word3,'  

I want to use a regex to convert either of the above 3 examples to "word1, word2, word3" - (Note: no comma after the last word in the result).

I used the following code:

import re
input_col = 'word1    ,   word2     , word3,    '
test_string = ''.join(input_col)
test_string = re.sub(r'[,\s]+', ' ', test_string)
test_string = re.sub(' +', ',', test_string)
print(test_string)  

I get the output as "word1,word2,word3,". Whereas I actually want "word1, word2, word3". No comma after word3.

What kind of regex and re methods should I use to achieve this?

4 Answers 4

3

you can use the split to create an array and filter len < 1 array

import re
s='word1    ,   word2     , word3,    '
r=re.split("[^a-zA-Z\d]+",s)
ans=','.join([ i for i in r if len(i) > 0 ])
Sign up to request clarification or add additional context in comments.

Comments

0

How about adding the following sentence to the end your program:

re.sub(',+$','', test_string)

which can remove the comma at the end of string

Comments

0

One approach is to first split on an appropriate pattern, then join the resulting array by comma:

string = 'word1,,,,,,,     word2,,,,,,     word3,,,,,,'
parts = re.split(",*\s*", string)
sep = ','
output = re.sub(',$', '', sep.join(parts))
print(output

word1,word2,word3

Note that I make a final call to re.sub to remove a possible trailing comma.

Comments

0

You can simply use [ ]+ to detect extra spaces and ,\s*$ to detect the last comma. Then you can simply substitute the [ ]+,[ ]+ with , and the last comma with an empty string

import re
input_col = 'word1    ,   word2     , word3,    '
test_string = re.sub('[ ]+,[ ]+', ', ', input_col) # remove extra space
test_string = re.sub(',\s*$', '', test_string) # remove last comma
print(test_string)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.