Page 1 of 1

Easy way to emulate str 'capitalize' function?

Posted: Tue Aug 16, 2022 6:09 am
by Jibun no kage
Easy way to emulate str 'capitalize' function? Since such is not part of the core of MP?

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

Posted: Tue Aug 16, 2022 6:41 am
by stijn
Something like s[0].upper() + s[1:] ? Or are you asking how to add this to micropython?

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

Posted: Tue Aug 16, 2022 6:56 am
by Roberthh
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()])

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

Posted: Sun Aug 21, 2022 7:01 pm
by Jibun no kage
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?

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

Posted: Sun Aug 21, 2022 7:08 pm
by Roberthh
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.