In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to use format in python". In daily operation, I believe many people have doubts about how to use format in python. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use format in python". Next, please follow the editor to study!
The specific usage is analyzed as follows:
The basic syntax of format is to replace the previous% through {} and:.
The format function can accept unlimited arguments and positions out of order.
Advantages of format:
Format is a new method for formatting strings in python2.6, which has many advantages over the old% format method.
1. Regardless of the data type, s can only replace the string type in the% method
two。 A single parameter can be output multiple times, and the order of the parameters can be different.
3. The filling mode is very flexible, and the alignment is very powerful.
4. The official recommended method,% method, will be eliminated in later versions.
Basic usage of format:
"Hello {0} {1}" .format ("Chen", "xin") # reference the first parameter # output 'Hello Chen xin' "{} is cute" .format ("Chen xin") # reference the first parameter # output' Chen xin is good' "My name is {name}" .format (name= "Chen xin") # reference the parameter named name # output'My name is Chen xin'
1. Type conversion
! s
! r
"Chen xin is a cute {! s}" .format ("baby") #! s is equivalent to calling str () # output 'Peppa pig is a cute baby' "Chen xin is a cute {! r}" .format ("baby") #! r equivalent to calling repr () # output "Peppa pig is a cute' baby'" for parameters
two。 Fill in a string by position
Print ('{0}, {1}, {2} '.format (' await, 'baked,' c')) # a, b, cprint ('{}, {}, {} '.format (' await,'c')) # a, cprint ('{2}, {0} '.format (' await,'c')) # c, aprint ('{2}, {0}'. Format (* 'abc')) # c Aprint ('{0} {1} {0} '.format (' aa', 'bb')) # aa bb aa
The same parameter can be filled multiple times. This is where format is more advanced than%.
3. Access parameters by name
Print ('name: {last_name} {first_name}' .format (last_name='chen', first_name='xin')) # name: chenxin name= {'last_name':' chen', 'first_name':' xin'} print ('name: {last_name}, {first_name}'. Format (* * name)) # name: chenxin
4. Access through parameter properties
Class MyList: def _ init__ (self, x, y): self.x, self.y = x, y def _ str__ (self): return 'MyList ({self.x}, {self.y})' .format (self = self) print (str (MyList ('Xiaoxin', 'www.xieniao.com')) # site name: Xiaoxin, address www.xieniao.com
5. Access through the items of parameters
My_list = ['Xiaoxin', 'www.xieniao.com'] print ("site name: {0 [0]}, address {0 [1]}" .format (my_list)) # "0" is required # site name: Xiaoxin, address www.xieniao.com
6. Align string
"{: > 5}" .format (1) # sets the width to 5 Right align "{: > 5}" .format (10) "{: > 5}" .format (100) "{: > 5}" .format (1000) # output the following result: '1percent' 10percent '100percent' 1000'print ('{: _ 30} '.format (' right aligned')) #'_ right aligned' print ('{: _ ^ 30} '.format (' centered')) # '_ centered_'
^ center back with width
< 左对齐 后面带宽度, >Align the rear band width to the right
The character with padding after the: sign can only be one character. If it is not specified, it is filled with spaces by default.
7. Truncate string
'{: .5}' .format ('Hello Chen') # truncate the first five characters # output' Hello'
8. Digital formatting
Print ("{: .2f}" .format (3.1415926)); # 3.14
+ means to display + before a positive number.
-negative number
(space) means to add a space before a positive number
B binary
D decimal system
O Octal
X hexadecimal
9. Use a comma as a thousand-bit separator
Print ('{:,} '.format (1234567890)) #' 1234567890'
10. Represents a percentage
Print ('number: {: 0.2%}' .format (0.61898)) # number: 61.90%
11. Time formatting
Import datetime d = datetime.datetime (2018, 7, 31, 15, 58, 58) print ('{:% Y-%m-%d% H:%M:%S} '.format (d)) # 2018-07-31 15:58:58
twelve。 Access elements in a tuple
A = (1pm 2)'X: {0 [0]}; Y: {0 [1]} '.format (a) # output' X: 1; Y: 2 format # Note: this feature is not supported for formatting strings with%
13. Access the elements in the dictionary
People = {"name": "Chen", "age": 18} "My name is {p [name]} and my age is {p [age]}" .format (p=people) # output'My name is Chen and my age is 18 characters # Note: this function is not supported by% formatting strings, so the study on "how to use format in python" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.