Ben Humphreys

  • Archive
  • RSS

Python Regex Global Replace

Today’s fun Python gotcha: I couldn’t find out how to do a global regular expression replace. In Perl it would look like:

$my_str =~ s/foo/bar/g;

In Python it’s:

import re
re.sub('foo', 'bar', my_text)

It turns out I wasn’t reading the sub() documentation properly. The amazing @puresock saved the day and pointed out this from the documentation:

The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous match, so sub('x*', '-', 'abc') returns '-a-b-c-'.

tl;dr Python’s regex-replace function sub() defaults to global. So you don’t need a global flag.

    • #programming
    • #python
  • 1 month ago
  • 4
  • Comments
  • Permalink
  • Share
    Tweet

4 Notes/ Hide

  1. benhumphreys posted this

Recent comments

Blog comments powered by Disqus
← Previous • Next →

About

Avatar Computational linguistics researcher at Kyoto University, focussing on machine translation. Also learning Japanese, Korean, French and other badassery.
(日本語版)

Me, Elsewhere

  • @benhumphreys on Twitter
  • benhumphreys on github
  • RSS
  • Random
  • Archive
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr