-2

I have a string as follows:

course_name = "Post Graduate Certificate Programme in Retail Management (PGCPRM) (Online)"

I want to extract only the 'PGCPRM' or whatever within the value within the first parenthesis and have a new course name as follows:

course_name_new = "Post Graduate Certificate Programme in Retail Management (Online)"
Iqbal
  • 2,094
  • 1
  • 20
  • 28

3 Answers3

2

You can use str.replace() :

>>> course_name = "Post Graduate Certificate Programme in Retail Management (PGCPRM) (Online)"
>>> course_name.replace('(PGCPRM) ','')
'Post Graduate Certificate Programme in Retail Management (Online)'

edit: if you want to replace the word before (Online) you need regex and a positive look-behind:

>>> re.sub(r'(\(\w+\) )(?=\(Online\))','',course_name)
'Post Graduate Certificate Programme in Retail Management (Online)'

Or if you want to remove the first parentheses use following :

>>> re.sub(r'(\(\w+\) ).*?','',course_name)
'Post Graduate Certificate Programme in Retail Management (Online)'

and for extract it use re.search :

>>> re.search(r'(\(.*?\))',course_name).group(0)
'(PGCPRM)'
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • No, I want to extract the value within the first parentheses whatever it is. Sorry for not mentioning that in the question. I will update this @kasra – Iqbal Jan 19 '15 at 11:55
2

Pretty simple:

In [8]: course_name
Out[8]: 'Post Graduate Certificate Programme in Retail Management (PGCPRM) (Online)'

In [9]: print re.sub('\([A-Z]+\)\s*', '', course_name)
Post Graduate Certificate Programme in Retail Management (Online)

In [17]: print re.search('\(([A-Z]+)\)\s*', course_name).groups()[0]
PGCPRM
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Dmitry Nedbaylo
  • 2,254
  • 1
  • 20
  • 20
1

To extract value within first parenthesis

>>> course_name = "Post Graduate Certificate Programme in Retail Management (PGCPRM) (Online)"
>>> x = re.search(r'\(.*?\)',course_name).group()
>>> x
'(PGCPRM)'

And then to replace

>>> course_name.replace(x,'')
'Post Graduate Certificate Programme in Retail Management  (Online)'
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140