Remix.run Logo
TZubiri 4 days ago

Here's my cheat sheet:

"STRING" + str(var) + "STRING"

Sohcahtoa82 3 days ago | parent | next [-]

I find "STRING {var} STRING" much more readable. Also, far easier to type. You don't even need to explicitly convert to a string first, it happens implicitly (Which, ironically, goes against the "Explicit is better than implicit" line in the Zen of Python).

But this page isn't about merely inserting a number/string into a string, it's about expressing how you want that number/string formatted. Maybe you only want the first two digits after a decimal. Maybe you want it to always be the same width and to pad with spaces or zeroes. Or any other ways of formatting.

metalliqaz 4 days ago | parent | prev | next [-]

Or even print("STRING", var, "STRING")

keep in mind that for long strings, each `+` creates a new string object (at least, it did in the 2.x days and I assume it hasn't changed)

zahlman 4 days ago | parent | next [-]

It has indeed not changed. But practically speaking it doesn't matter much. The string implementation cheats by using resizable buffers internally for at least some purposes, while presenting an immutable-type interface. But regardless, a given line of code is going to have O(1) such additions; it's not remotely as bad as `for i in items: str += foo(i)`. (This should be done using `''.join` instead.)

TZubiri 4 days ago | parent | prev [-]

#Takes around 1 second s="a"*3000000000

#instant, does not consume twice as much memory. s+="a"

I don't know the internals, but certainly there's not a new string being created. Maybe if it exceeds capacity? Who cares at that point, it's python strings, not Matmuls in C.

4 days ago | parent | prev [-]
[deleted]