Formatting strings with ". format" and "%"

Asked

Viewed 15,185 times

2

It’s been a while since I’ve been studying some python code.

Some people format 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 point is:

Is there any difference between these two forms? Whether in the performance question or something like that?

  • 1

    Obviously there is, but there are tiny differences and you shouldn’t even worry about real applications.

  • I imagined that there would be no real difference, but I was really curious to know why python presents two solutions to the same problem. Since one of the phrases from PEP 20 is "There must be one, and preferably just an obvious way to do it."

  • 1

    @LINQ There are differences and new very interesting features that, in my opinion, should be taken into account.

  • Now there is a form called F-string that is more legible and performative. If you want to take a look in this post has some basic examples.

2 answers

5


Yes, it has several differences, several improvements, in addition to the new style being much more elegant and pythonico, in my opinion. I haven’t read anywhere, it’s just achism, but I believe the old style is maintained for compatibility with legacy code.

I put below some differences, in fact, I chose the ones that I could not do in the old format, of course I did not put all, but only the ones that I found more interesting, for access to all the Features, see the documentation.

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

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

Choose a character for pad:

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

Centralization:

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

        teste 

Arguments in the 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'
  • 1

    You should mention that the same "new style" are the f-strings - these yes, finally more practical than the operator %.The method .format, despite offering a good control of how things are interpolated, has always been very verbose compared to the operator %.

  • True, there are so many resources in python, right? I don’t even remember if I answered the question I had already used the f-strings.

1

In the new update there is another option:

um = 1
dois = 2

print(f'valor1:{um} valor2:{dois}')

#output: valor1:1 valor2:2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.