Why does `'{x[1:3]}’.format(x=”asd”)` cause a TypeError?

An experiment based on your comment, checking what value the object’s __getitem__ method actually receives: class C: def __getitem__(self, index): print(repr(index)) ‘{c[4]}’.format(c=C()) ‘{c[4:6]}’.format(c=C()) ‘{c[anything goes!@#$%^&]}’.format(c=C()) C()[4:6] Output (Try it online!): 4 ‘4:6’ ‘anything goes!@#$%^&’ slice(4, 6, None) So while the 4 gets converted to an int, the 4:6 isn’t converted to slice(4, 6, None) as … Read more

How do I convert a string into an f-string?

f-strings are code. Not just in the safe, “of course a string literal is code” way, but in the dangerous, arbitrary-code-execution way. This is a valid f-string: f”{__import__(‘os’).system(‘install ransomware or something’)}” and it will execute arbitrary shell commands when evaluated. You’re asking how to take a string loaded from a text file and evaluate it … Read more

f-strings vs str.format()

I’m afraid that it will be deprecated during the next Python versions Don’t be, str.format does not appear (nor has a reason) to be leaving any time soon, the PEP that introduced fprefixed-strings even states in its Abstract: This PEP does not propose to remove or deprecate any of the existing string formatting mechanisms. Formatted … Read more

In Python format (f-string) strings, what does !r mean? [duplicate]

It just calls the repr of the value supplied. It’s usage is generally not really needed with f-strings since with them you can just do repr(self.radius) which is arguably more clear in its intent. !r (repr), !s (str) and !a (ascii) were kept around just to ease compatibility with the str.format alternative, you don’t need … Read more

How can I use newline ‘\n’ in an f-string to format output?

You can’t. Backslashes cannot appear inside the curly braces {}; doing so results in a SyntaxError: >>> f'{\}’ SyntaxError: f-string expression part cannot include a backslash This is specified in the PEP for f-strings: Backslashes may not appear inside the expression portions of f-strings, […] One option is assinging ‘\n’ to a name and then … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)