Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting expressions (Python)

String formatting expressions:

'This is %d %s example!' % (1, 'nice')

String formatting method calls:

'This is {0} {1} example!'.format(1, 'nice')

I personally prefer the method calls (second example) for readability but since it is new, there is some chance that one or the other of these may become deprecated over time. Which do you think is less likely to be deprecated?

like image 996
eozzy Avatar asked Nov 19 '09 13:11

eozzy


People also ask

What is a string formatting expression?

String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text. custom_string = "String formatting" print(f"{custom_string} is a powerful technique") String formatting is a powerful technique.

What is %s and %D in Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42))

What is __ format __ in Python?

The __format__() method is used by string. format() as well as the format() built-in function. Both of these interfaces are used to get presentable string versions of a given object.


1 Answers

Neither; the first one is used in a lot of places and the second one was just introduced. So the question is more which style you prefer. I actually prefer the dict based formatting:

d = { 'count': 1, 'txt': 'nice' }
'This is %(count)d %(txt)s example!' % d

It makes sure that the right parameter goes into the right place, allows to reuse the same parameter in several places, etc.

like image 122
Aaron Digulla Avatar answered Oct 23 '22 16:10

Aaron Digulla