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
Formatting numbers¶
Output | f-string field |
---|---|
'4125.60' | {n:.2f} |
'4,125.60' | {n:,.2f} |
'04125.60' | {n:08.2f} |
'37%' | {p:.0%} |
r
aw or r
egex strings¶
- raw string to ignore
- JS has String.raw
- see the readable regex section
r
egex 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¶
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_plus
¶
- replaces spaces with
+
- instead of
%20
quote vs quote_plus
Last update:
2023-04-24