Here's a short one...
Sometimes I find myself wanting to pretty up a string. For example, a value might come in all in lower case letters and I want to capitalize the first letter or maybe go for capitalizing all first letters. Another use case is using variable names (conventionally all lower case) for captions.
- 'this is my string' ===> 'This is my string'
- 'top values' ===> 'Top Values'
Python has title() and capitalize() functions but these are not implemented in CircuitPython.
Also, strings may be in camel case that I want to fix - the Weather Powerup on AdafruitIO sends text data back this way:
- 'mostlyClear' ===> 'Mostly Clear'
When there is a limited set of data I've used if/elif/else statements or used look-up dictionaries, but in some cases the inputs may not be known. Also, who wants to write all of the repetitive code!
Since CircuitPython does include upper() and lower() functions we can build functions to do this. So with the help of CoPilot I drafted and now include these three functions in my code when I am doing anything with strings:
def title_case(s):
if len(s) > 3:
words = s.split()
titled = [word[0].upper() + word[1:].lower() if len(word) > 0 else '' for word in words]
return ' '.join(titled)
else:
return s
def capitalize_case(s):
if len(s) > 3:
return s[0].upper() + s[1:].lower()
else:
return s
def camel_to_title_case(s):
chars = []
for i, char in enumerate(s):
if char == '_':
chars.append(" ")
elif char.isupper() and i != 0:
chars.extend([" ", char])
else:
chars.append(char)
return ''.join(chars)
In these sample functions I only apply to strings that are greater than three characters long as generally when I have short strings, I want them to keep the case (such as 'MPH'). But you can change this if you want it to make the change to all input strings. In the camel_to_title() function I also replace underscores with spaces, primarily for when I use variable names as captions.
Hope you find this useful - and be sure to share any custom functions you can't live without.
This page (CircuitPython Functions to Pretty Up Strings ) was last updated on February 12, 2026.