Skip to content

Python String Formatting

String methods to memorize

Method Related Methods Description
join Join iterable of strings by a separator
split rsplit Split (on whitespace by default) into list of strings
replace Replace all copies of one substring with another
strip rstrip & lstrip Remove whitespace from the beginning and end
casefold lower & upper Return a case-normalized version of the string
startswith Check if string starts with 1 or more other strings
endswith Check if string ends with 1 or more other strings
splitlines Split into a list of lines
format Format the string (consider an f-string before this)
count Count how many times a given substring occurs
removeprefix Remove the given prefix
removesuffix Remove the given suffix

String formatting

https://www.pythonmorsels.com/string-formatting/

f strings

f-string debugging

Prints out both the var name and the value

>>> python = 3.8
>>> f"{python=}"
'python=3.8'

Formatting numbers

>>> p = 0.374
>>> print(f"{p:.1%} full")
37.4% full
Output f-string field
'4125.60' {n:.2f}
'4,125.60' {n:,.2f}
'04125.60' {n:08.2f}
'37%' {p:.0%}

raw or regex strings

regex strings

Template strings

  • less powerful than f strings
  • useful for (malicious) user input
from string import Template
templ_string = 'Hey $name, there is a $error error!'
Template(templ_string)
    .substitute(
        name=name,
        error=hex(errno))

Nicer multi-line strings

from textwrap import dedent

def copyright():
    print(dedent("""
        Copyright (c) 2022
        All Rights Reserved.
    """).strip("\n"))

Title case

Avoid "str".title() alone

>>> "don't".title()
"Don'T"

Use a regex

import re

def title(value: str) -> str:
    titled = value.title()

    # Lowercase the whole regular expression match group.
    lowercase_match = lambda match: match.group().lower()

    titled = re.sub(r"([a-z])'([A-Z])", lowercase_match, titled)  # Fix Don'T
    titled = re.sub(r"\d([A-Z])", lowercase_match, titled)  # Fix 1St and 2Nd
    return titled

Use a library like titlecase if you want small words (like is and a) to be lower case

urllib.parse.quote

escape characters to put stuff in the URL

urllib.parse — Parse URLs into components

>>> quote('/El Niño/')`
'/El%20Ni%C3%B1o/'

quote_plus

  • replaces spaces with +
  • instead of %20

quote vs quote_plus


Last update: 2023-04-24