Micropython String

RP2040 based microcontroller boards running MicroPython.
Target audience: MicroPython users with an RP2040 boards.
This does not include conventional Linux-based Raspberry Pi boards.
Post Reply
srogers
Posts: 11
Joined: Sun Feb 06, 2022 12:25 am

Micropython String

Post by srogers » Thu Feb 17, 2022 6:47 am

I was looking at print formatting with MicroPython and RP2.

Specifically I was trying to use:

Code: Select all

print("foo".ljust(50))
I was unable to do thing because the REPL reports that there is no method ljust for str.

And, sure enough, in MicroPython 1.18 ljust (and rjust) do not exist as methods to str.

Code: Select all

help ("foo")
object foo is of type str
  encode -- <function>
  find -- <function>
  rfind -- <function>
  index -- <function>
  rindex -- <function>
  join -- <function>
  split -- <function>
  splitlines -- <function>
  rsplit -- <function>
  startswith -- <function>
  endswith -- <function>
  strip -- <function>
  lstrip -- <function>
  rstrip -- <function>
  format -- <function>
  replace -- <function>
  count -- <function>
  partition -- <function>
  rpartition -- <function>
  center -- <function>
  lower -- <function>
  upper -- <function>
  isspace -- <function>
  isalpha -- <function>
  isdigit -- <function>
  isupper -- <function>
  islower -- <function> 
Why is there no ljust or rjust, when it is shown as examples to use for formatting?

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

Re: Micropython String

Post by stijn » Thu Feb 17, 2022 7:04 am

Perhaps you were looking at CPython examples?

MicroPython indeed does not implement those functions: http://docs.micropython.org/en/latest/g ... s.html#str

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Micropython String

Post by pythoncoder » Thu Feb 17, 2022 9:08 am

So write your own:

Code: Select all

def rjust(s, n):
    return "".join((" "*(n - len(s)), s))
print(rjust("foo", 50))
                                               foo
Or as a one-liner

Code: Select all

ljust = lambda s, n : "".join((s, " "*(n - len(s))))
Peter Hinch
Index to my micropython libraries.

bulletmark
Posts: 59
Joined: Mon Mar 29, 2021 1:36 am
Location: Brisbane Australia

Re: Micropython String

Post by bulletmark » Thu Feb 17, 2022 10:27 pm

Code: Select all

print(f'{"foo":<50s}')

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Micropython String

Post by pythoncoder » Fri Feb 18, 2022 12:29 pm

Much better ;)
Peter Hinch
Index to my micropython libraries.

Post Reply