Page 1 of 1

Micropython String

Posted: Thu Feb 17, 2022 6:47 am
by srogers
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?

Re: Micropython String

Posted: Thu Feb 17, 2022 7:04 am
by stijn
Perhaps you were looking at CPython examples?

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

Re: Micropython String

Posted: Thu Feb 17, 2022 9:08 am
by pythoncoder
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))))

Re: Micropython String

Posted: Thu Feb 17, 2022 10:27 pm
by bulletmark

Code: Select all

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

Re: Micropython String

Posted: Fri Feb 18, 2022 12:29 pm
by pythoncoder
Much better ;)