Baywatch
Baywatch

Reputation: 423

Convert this perl replacement to python

I am trying to port some perl code over to python. Not being proficient in perl is a challange, but I've got most of it done. There is one function however that performs a word replacement which I don't know if there is a straight-forward python equivelent.

$my_string =~ s/^(.*?) \(The\)$/The $1/;
$my_string=~ s/\bL\.? ?L\.? ?C\.?\b//;
$my_string =~ s/[(),]//g;

I suppose that I could use something such as:

re.sub('s/^(.*?) \(The\)$', '$/The 1/', my_string)

for the first sample, but I am clueless as to the others.

Thanks for any insight.

Upvotes: 0

Views: 102

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122322

You need to remove the s/ and / parts here, and use \1 for back references. Using raw strings makes this workable:

my_string = re.sub(r'^(.*?) \(The\)$', r'The \1', my_string)
my_string = re.sub(r'\bL\.? ?L\.? ?C\.?\b', '', my_string)
my_string = re.sub(r'[(),]', '', my_string)

These replacements are 'global' by default (what the g flag does); add a integer count as a 4th argument if you need to limit this:

my_string = re.sub(r'^(.*?) \(The\)$', r'The \1', my_string, 1)
my_string = re.sub(r'\bL\.? ?L\.? ?C\.?\b', '', my_string, 1)
my_string = re.sub(r'[(),]', '', my_string)

Upvotes: 6

Related Questions