python basics 09_ string formatting

First, use the method of %s.

#!/usr/bin/env python
# coding:utf-8

#without format method, use %s and %d 

name = ' Tom ' 
age = 100

msg = " %s is a good man, you can live to %d years old. " % (name,age) # %d can only pass numbers, so it is most convenient to use %s to 
print (msg)

#Intercepting the string 
title = "The average price of all provinces and cities across the country has risen by 30% " 
ms = " Today's important news is: %.9s " % title   #Intercepted 9 digits, which can be used to control the length 
print (ms)

#Print floating point number 
tpl = " Received %.2f dollars today " % 99.325452 #Only 2 decimal places are reserved and rounded up 
print (tpl)

#Print percentage with %% 
tpl = " Completed %.2f%% " % 99.325452 #Only keep 2 decimal places and round up 
print (tpl)

#Use the way of passing a dictionary 
tmp = " I am %(name)s age %(age)d " % { " name " : ' Elly ' , ' age ' :88 }
 print (tmp)

tp = "I am \033[45;1m%(name)+20s\033[0m age %(age)d" % {"name":'Elly','age':88}
print(tp)

print('root','x','0','0',sep=':')

Next, look at some of the methods of format.

For more information: http://www.cnblogs.com/wupeiqi/articles/5484747.html

#!/usr/bin/env python
# coding:utf-8


tpl = 'I am {name}, age {age}, really {name}'.format(name='Tom', age=22) # 传Key
print(tpl)

tpl = ' I am {name}, age {age}, really {name} ' .format(**{ ' name ' : ' Jerry ' , ' age ' :33}) #Passing a dictionary with two asterisks is equivalent to passing a dictionary Convert to the format of the line above. 
print (tpl)

tpl = ' I am {0[0]}, age {1[0]}, really {1[2]} ' .format([1,2,3],[11,22,33]) #Pass list 
print (tpl)

tpl = ' I am {:s}, age {:d}, really {:f} ' .format( ' Sen ' ,18,88.999) #Transfer dictionary print 
( tpl)

# # This reference: http://www.cnblogs.com/wupeiqi/articles/5484747.html 

l = [ " seven " , 18 ]
tpl = " i am {:s}, age {:d} " .format(*l) #The asterisk means to traverse the elements in the list and then pass it to 
print (tpl)

tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
print(tpl)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324632663&siteId=291194637