30 - format string methods

A method string format There are several methods specified parameters

  • Default (parameter passed in correspondence with {})
  • Named parameters
  • Location parameters {2}

2. The method of format strings described in detail how the format string

s1 = 'Today is {}, the temperature is {} degress.'

print(s1.format('Saturday', 24))
Today is Saturday, the temperature is 24 degress.
s2 = 'Today is {day}, the temperature is {degree} degress.'
print(s2.format(degree = 30, day = 'Sunday'))
Today is Sunday, the temperature is 30 degress.
s3 = 'Today is {day},{} the {} temperature is {degree}'
print(s3.format('abcd' , 12345, degree=24, day='Sunday'))
Today is Sunday,abcd the 12345 temperature is 24
s4 = 'Today is {day}, {1}, the {0} temperature is {degree} degrees.'
print(s4.format('abcd', 12345, degree=24, day='Sunday'))
Today is Sunday, 12345, the abcd temperature is 24 degrees.
class Person:
    def __init__(self):
        self.age = 20
        self.name = 'Bill'
    
person = Person()

s5 = 'My name is {p.name}, my age is {p.age}'
print(s5.format(p = person))
My name is Bill, my age is 20

31 - Let the string centered

Ruo
Published 131 original articles · won praise 134 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_29339467/article/details/104395810