user3234810
user3234810

Reputation: 482

regular expression re.sub for string formatting in python

Quite new to regular expressions and am trying to get a grasp on them

string = "regex_learning.test"
subbed = re.sub(r'(.*)_learning(.*), r'\1', string)

What I was hoping for is "regex.test" as an ouput when printing subbed, however I just get "regex"

Could someone explain why I am losing the .test?

Thanks in advance

Upvotes: 1

Views: 1787

Answers (1)

Shailen Tuli
Shailen Tuli

Reputation: 14171

Use this:

subbed = re.sub(r'(.*)_learning(.*)', r'\1' + r'\2', string)

You can also write it as:

subbed = re.sub(r'(.*)_learning(.*)', "%s%s" % (r'\1', r'\2'), string)

Upvotes: 2

Related Questions