Easy way to emulate str 'capitalize' function?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Jibun no kage
Posts: 144
Joined: Mon Jul 25, 2022 9:45 pm

Easy way to emulate str 'capitalize' function?

Post by Jibun no kage » Tue Aug 16, 2022 6:09 am

Easy way to emulate str 'capitalize' function? Since such is not part of the core of MP?

stijn
Posts: 735
Joined: Thu Apr 24, 2014 9:13 am

Re: Easy way to emulate str 'capitalize' function?

Post by stijn » Tue Aug 16, 2022 6:41 am

Something like s[0].upper() + s[1:] ? Or are you asking how to add this to micropython?

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Easy way to emulate str 'capitalize' function?

Post by Roberthh » Tue Aug 16, 2022 6:56 am

Simething like:

>>> s="the quick brown fox jumps over the lazy dog"
>>> " ".join([w[0].upper() + w[1:] for w in s.split()])

'The Quick Brown Fox Jumps Over The Lazy Dog'

Edit:
Or to exclude 1 character items from capitalization:

" ".join([w[0].upper() + w[1:] if len(w) > 1 else w for w in s.split()])

Jibun no kage
Posts: 144
Joined: Mon Jul 25, 2022 9:45 pm

Re: Easy way to emulate str 'capitalize' function?

Post by Jibun no kage » Sun Aug 21, 2022 7:01 pm

Serves me right... right after I posted the question... I remembered the upper() trick. Thanks guys, for the examples, validation appreciated. Adding it to MP? Nah, not sure there is a need when the upper trick works. Would adding it to MP really save resources over the upper() trick?

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Easy way to emulate str 'capitalize' function?

Post by Roberthh » Sun Aug 21, 2022 7:08 pm

Adding it to MP? Nah, not sure there is a need when the upper trick works.
I would say no, given that memory is a scarce resource at micros. Because it is rarely requested and easy to implement.

Post Reply