Use removesuffix
for safe suffix removal in Python 3.9+ (there's also removeprefix
) 🐍
Benefits:
• Presence check: it ensures the suffix is present before attempting to remove it.
• Explicitness: it explicitly specifies which suffix to remove, thus avoidiang ambiguity.
• More readable: clearly named methods. 😍
# Less safe:
# Assuming the name is formatted like '[index]'
name = name[1:-1]
# Safer and better:
# Remove '[' prefix and ']' suffix if they are present
name = name.removesuffix('[').removesuffix(']')
You might wonder if you can achieve the same thing using rstrip + lstrip, but they might remove more than you want if there are multiple occurrences of the specified characters, e.g.:
>>> name = "[[index]]"
>>> name.lstrip('[').rstrip(']')
'index'
>>> name.removeprefix('[').removesuffix(']')
'[index]'
#strings