create dynamic strings

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
jedie
Posts: 228
Joined: Fri Jan 29, 2016 12:32 pm
Contact:

create dynamic strings

Post by jedie » Fri Nov 29, 2019 11:18 am

https://docs.micropython.org/en/latest/ ... d.html#ram says:
The best way to create dynamic strings is by means of the string format() method:

Code: Select all

var = "Temperature {:5.2f} Pressure {:06d}\n".format(temp, press)
What's about the old school %-formatter method? Is the RAM allocation the same?!?

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

Re: create dynamic strings

Post by Roberthh » Fri Nov 29, 2019 1:53 pm

Probably yes. Both the format string and the generated target need RAM.

User avatar
jimmo
Posts: 1004
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia

Re: create dynamic strings

Post by jimmo » Sun Dec 01, 2019 11:08 am

Definitely yes. They work in the same way, by appending to a vstr which grows as the string is generated.

The reason that ''.format() is preferred over % is that not all ports of MicroPython have % enabled.

jedie
Posts: 228
Joined: Fri Jan 29, 2016 12:32 pm
Contact:

Re: create dynamic strings

Post by jedie » Sun Dec 01, 2019 4:28 pm

jimmo wrote:
Sun Dec 01, 2019 11:08 am
The reason that ''.format() is preferred over % is that not all ports of MicroPython have % enabled.
Oh, interesting. Then it is probably best to prefer .format().

jedie
Posts: 228
Joined: Fri Jan 29, 2016 12:32 pm
Contact:

Re: create dynamic strings

Post by jedie » Sun Dec 01, 2019 5:06 pm

What's about this:

Code: Select all

print('Some Text:', variable)
I don't think this should be an unnecessary waste of RAM either, is it?

User avatar
jimmo
Posts: 1004
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia

Re: create dynamic strings

Post by jimmo » Sun Dec 01, 2019 11:49 pm

That's right, this doesn't require any allocations -- it just prints the strings directly.

Post Reply