Regex: remove 's from a string?

Viewed 234

string input: Python's Programming: is very easy to learn

expected output: Python Programming: is very easy to learn

Here is what I have so far which isn't working:

import re
mystr = "Python's Programming: is very easy to learn"
reg = r'\w+'
print(re.findall(reg, mystr))

How do I remove the 's from python's?

2 Answers

You extract all matches of one or more alphanumeric characters.

Use

\b's\b

See proof.

Explanation:

--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  's                       '\'s'
--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char

Python code:

import re
mystr = "Python's Programming: is very easy to learn"
print(re.sub(r"\b's\b", '', mystr))

Here are two options. The first uses regex, and the second uses the string replace method.

import re
mystr = "Python's Programming: is very easy to learn"
reg = r"'s"
print(re.sub(reg, '', mystr))
   # prints: Python Programming: is very easy to learn
print(mystr.replace("'s",''))
   # prints: Python Programming: is very easy to learn
Related