Not quite sure if% s is in Python, help?

I am learning Python from a book right now, and I can’t understand what is the point of using% s to place a specific item in a list, line, dictionary, etc.

For instance:

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

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

Both teams print "Cohen" that the dot ever uses% s?

+3
source share
5 answers

The idea is to let you easily create more complex output, like

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

instead

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

However, since you are just starting to use Python, you should immediately start learning the new string formatting syntax :

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

, . , ( , ):

>>> '{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'

..

+14

% s python .

a = 1.23
print "The value is %0.5f" %(a) # prints 1.23000
+3

%s .

python, , . , , , .

%s, , , , , .

, , , , + , .

+2

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

.

(n1, n2, n3) , . .

( " " % (n1, n2, n3)), "" . , , .

+2

Use %sis simply a use of what I would call a format printf. He is familiar with programming languages ​​such as C. As Tim noted, python has a new preferred way to format strings, which you should probably learn. But the old way is still quite powerful. Try to man sprintfsee how you can specify flags, field width, precision, etc. I think python printing is compatible with all of this.

0
source

Source: https://habr.com/ru/post/1786856/


All Articles