A string format (% and format)
1.% s string type main receiver may also receive any type
tp1 = "i am %s my hobby is alex" % 'lhf' print(tp1)
tp1 = "i am %s my hobby is %s" % ('lhf', 'dabai') print(tp1)
、
tp1 = "i am %s my age is %d" % ('lhf', 11) tp2 = "1 am %s my age is %s" % ('dabai', 12) print(tp1, tp2, sep="\n")
Note:% d receives only number,% s receive any type, but preferably the best use, easy to maintain!
2. Print a float, the default retention six decimal places, automatic rounding.
tp1 = "percent %f"% 99.99675854 tp2 = "percent %.3f"% 99.99975854 print(tp1) print(tp2)
3. Print Percentage
tp1 = "percent %.3f%%"% 99.99635854 print(tp1)
4. The value of incoming Dictionary
tp1 = "i am %(name)s age %(age)d" %{"name": "alex", "age": 18} print(tp1)
tp1 = "i am %(pp).2f" % {"pp": 99.99} print(tp1)
5. Optional: + right aligned - left aligned behind the figures represents the width, the color of the following controls 42
msg = "i am %(name) + 30s my hobby is dabai" % {'name': 'liu'} msg2 = "i am \033[42;1m%(name) + 30s\033[0m my hobby is dabai" % {'name': 'liu'} print(msg) print(msg2)
Two, format usage:
1. The sequence corresponds to
tp1 = "i am {} age {} {}".format("alex", 18, "alex") print(tp1)
The index corresponds to the back 2
tp1 = "i am {2} age {1} {0}".format("alex", 18, "dabai") print(tp1)
3. When the dictionary is passed, preceded by two note **
tp1 = "i am {name} age {age} really {name}".format(name = "alex", age = 18) tp2 = "i am {name} age {age} really {name}".format(**{"name": "alex", "age": 18}) print(tp1) print(tp2)
4. The index list corresponding to
tp2 = "i am {0[0]} age {0[1]} really {0[2]}".format(["dabai","22","aaa"],[1,2,3]) print(tp2)
The value corresponding to the type input in order
tp2 = "i am {:s} age {:d} really {:.2f}".format("dabai", 18, 99.9) print(tp2)
6. Under this type, if the incoming value of the list, to the front with *
tp2 = "i am {:s} age {:d} really {:.2f}".format(*["dabai", 18, 99.9]) print(tp2)
7. Different hexadecimal Demo (x: lowercase hexadecimal, X: uppercase hexadecimal, o: 8 hex, b: 2 Hex)
tp1 = "number: {:b} {:o} {:d},{:x}, {:X}, {:.2%}".format(15, 15, 15, 15,15,15.2341234) print(tp1)
tp1 = "number: {0:b} {0:o} {0:d},{0:x}, {0:X}, {0:.2%}".format(15) print(tp1)
TP1 = "number, whether {b} {num whether O} {d}, {whether x}, {Surely, 10}, {whether: .2%}". format (whether = 15) print ( TP1)