Replace First and Last Word of String in the Most Pythonic Way

python, python-2.7

Solution

import re
a = " this is a demonstration sentence. "
print(re.sub(r'''(?x)      # VERBOSE mode
             (             # 
              ^            # start of string
              \s*          # zero-or-more whitespaces 
              \w           # followed by an alphanumeric character
              )        
             |             # OR
             (
             \w            # an alphanumeric character
             \S*           # zero-or-more non-space characters
             \s*           # zero-or-more whitespaces
             $             # end of string
             )
             ''',
             lambda m: m.group().title(),
             a))

yields

 This is a demonstration Sentence. 

Problem

I am looking for the most pythonic way to replace the first and last word of a string (doing it on a letter basis won't work for various reasons). To demonstrate what I'm trying to do, here is an example. ``` a = "this is the demonstration sentence." ``` I'd like the result of my python function to be: ``` b = "This is the demonstration Sentence." ``` The tricky part of it is that there might be spaces on the front or the end of the string. I need those to be preserved. Here's what I mean: ``` a = " this is a demonstration sentence. " ``` The result would need to be: ``` b = " This is a demonstration Sentence. " ``` Would also be interested in opinions on whether a regex would do this job better than python's inbuilt methods, or vice versa.

Original source