Q:

Pandas Pattern Matching Add Text

I have a pandas dataframe dfdata that has a field "fieldname" with string data in it, with substring entries like "then value)".  I would like to replace these entries with something like "then value end)".  The problem is the "value" is different for different rows and the strings contain multiple ")".  So str.replace won't work.  I was thinking maybe something like re.sub with a wildcard, but I need the wild card value to show up in the replacement.  I was thinking I might need to write a loop. Does anybody know a slick way to do this?  I have example data and output below.
Example Data:

import pandas as pd
dfdata = pd.DataFrame({'fieldname1': ['Bob', 'Jane'], 
                   'fieldname2': ['Other words when spaghetti then turnip), do this)', 'Different other words when tomato then ketchup)']})

Example Output:

import pandas as pd
dfdata = pd.DataFrame({'fieldname1': ['Bob', 'Jane'], 
                   'fieldname2': ['Other words when spaghetti then turnip end), do this)', 'Different other words when tomato then ketchup end)']})

A:

IIUC:
In [36]: dfdata['fieldname2'] = \
             dfdata['fieldname2'].str.replace(r'(\s*then\s*)(\w+)\)', r'\1\2 end)')

In [37]: dfdata
Out[37]:
  fieldname1                                             fieldname2
0        Bob  Other words when spaghetti then turnip end), do this)
1       Jane    Different other words when tomato then ketchup end)

