Formatting strings with ".format" and "%"

1

It's been a while since I've been studying some python code that I come across this situation.

Some people format the code using ".format":

fruta = "Maça"
print("Eu gosto de {0}!".format(fruta))

And others use the "%"

fruta = "Maça"
print("Eu gosto de %s!" % fruta)

My question is:

Is there any difference between these two forms? Whether it's the performance issue or something?

    
asked by anonymous 31.07.2017 / 22:08

1 answer

4

Yes, there are several differences, several improvements, and the new style is much more elegant and pythonic in my opinion. I have not read it anywhere, it's just flattering, but I believe the old style is maintained for compatibility with legacy code.

I put some differences below, in fact, I chose those that I could not do in the old format, of course I did not put all of them, but only the ones I found most interesting, for access to all the features, get the documentation.

With the new style you can clarify the position of the argments:

'{1} {0}'.format('Um', 'Dois')
Dois Um

Choose a pad character:

'{:_<9}'.format('teste')
teste____

Centralization:

'{:^10}'.format('teste')

        teste 

Arguments in keys:

'{nome} {sobrenome}'.format{sobrenome='Silva', nome='José')
'José Silva'

Access to data structures (dict and list in the example):

pessoa = {'nome': 'José', 'sobrenome': 'Silva'}
'{p[sobrenome]} {p[nome]}'.format(p=pessoa)    
'Silva José'

data = [9, 2, 43, 18, 32, 77, 99] 
'{d[3]} {d[6]}'.format(d=data)
'18,99'
    
31.07.2017 / 23:55