Format strings vs concatenation
I see many people using format strings like this:
I see many people using format strings like this:
I’ve been working on a text-based game in Python, and I’ve come across an instance where I want to format a string differently based on a set of conditions.
I need to find out how to format numbers as strings. My code is here:
If I write in Python: data = {'n': 3, 'k': 3.141594, 'p': {'a': 7, 'b': 8}} print('{n}, {k:.2f}, {p[a]}, {p[b]}'.format(**data)) del data['k'] data['p']['b'] = None print('{n}, {k:.2f}, {p[a]}, {p[b]}'.format(**data)) I get: 3, 3.14, 7, 8 Traceback (most recent call last): File "./funky.py", line 186, in <module> print('{n}, {k:.2f}, {p[a]}, {p[b]}'.format(**data)) KeyError: 'k' Instead of an … Read more
I hit this TypeError exception recently, which I found very difficult to debug. I eventually reduced it to this small test case:
On Learn Python the Hard Way page 21, I see this code example: x = "There are %d types of people." % 10 … print "I said: %r." % x Why is %r used here instead of %s? When would you use %r, and when would you use %s? Answers: Thank you for visiting the … Read more
Is it possible to do partial string formatting with the advanced string formatting methods, similar to the string template safe_substitute() function?
I want to provide automatic string formatting in an API such that:
Given a dictionary of ints, I’m trying to format a string with each number, and a pluralization of the item.