6

You're not sure what the% s point is in Python, do you help?

 3 years ago
source link: https://www.codesd.com/item/you-re-not-sure-what-the-s-point-is-in-python-do-you-help.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

You're not sure what the% s point is in Python, do you help?

advertisements

I'm learning Python from a book right now and I can't figure out what the point is of using the %s to site a specific item in a list, string, dictionary, etc.

For example:

names = ["jones", "cohen", "smith", "griffin"]

print(names[1])
print("%s" % names[1])

Both commands print "cohen," what's the point of ever using the %s?


The idea is to allow you to easily create more complicated output like

print("The name is %s!" % names[1])

instead of

print("The name is " + names[1] + "!")

However, as you're just starting to use Python, you should start learning the new string formatting syntax right away:

print("The name is {}!".format(names[1])

Of course, this example can't show the real power of string formatting methods. You can do much more with those, for example (taken from the docs linked above):

>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'
>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

and so on...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK