Replacing Python's title() Function for Custom Needs

Small confession: I’ve never really liked Python’s .title(). It seems fine at first, but the more you use it, the more little issues show up. Acronyms get mangled, edge cases slip through, and your nicely formatted text starts looking slightly off. After running into this a few times, I ended up writing a version that behaves closer to what I expect: title_case = lambda s: re.sub( r"[A-Za-z]+(?:'[A-Za-z]+)?", lambda m: ( lambda w, b: w if re.fullmatch(r"[A-Z]+(\.[A-Z]+)*\.?", b) else w if not (b.islower() or b.isupper()) else w.capitalize() )(m.group(0), m.group(0).split("'")[0]), s ) It is simple, but it handles a few things better for my use cases: • Keeps acronyms like “NASA” and “U.S.A.” intact • Leaves mixed-case words as they are • Handles basic apostrophes more cleanly It is not perfect, but it works better for the cases I run into most often. It also made me realize that built-in functions are not always the best fit. Sometimes you need something slightly different for your own context. Curious to hear, what is a built-in function you have replaced or wrapped because it did not quite do what you needed? #Python #Programming #SoftwareDevelopment #Coding #DeveloperLife #AIWithAnishArya

  • text

To view or add a comment, sign in

Explore content categories