Tuesday, 15 January 2013

python - Regular expression to reverse order of words in a string -



python - Regular expression to reverse order of words in a string -

i have been given sentence in 2 words separated comma:

i.e.

the big, fast bug ate slower one.

and asked write regular look reverse order of 2 words comma prints:

'the fast, big bug...'

what have far:

i thinking involves findall comma , space , reverse function of sort.

you need re.sub() as:

>>> a="the big, fast bug ate slower one. quick, brownish fox jumps on lazy dog" >>> re.sub(r'\s(\w*),\s+(\w*)\s',r' \2, \1 ',a) 'the fast, big bug ate slower one. brown, quick fox jumps on lazy dog'

it substitutes words separated ',' same words in reverse order, leaving rest of string is.

python regex

No comments:

Post a Comment