In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of how to format the Python string, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this Python string formatting article. Let's take a look at it.
What is formatting?
Definition: a string in which some members (elements) of a fixed string change according to the value of the variable. This is string formatting.
Take a small chestnut in life: for example, our schoolbags, our schoolbags are fixed. But we may put different things we need to carry into our schoolbags every day. The schoolbag here is like a "fixed string", and the different items in the bag every day are like "strings that change according to the value of the variable".
Let's combine the code example to understand what a formatted string is more intuitively. The example is as follows:
# Today is Date, Week # Date here, we replace it with 'January 1st, 2000'; Week, we replace it with'- 'Date =' January 1st, 2000 'Week ='-'print (' today is'+ str (Date) + week'+ Week) # Date and Week will output today's date and day of the week as the value changes; this is the formatting of the string. Use formatted scenarios and purposes
When sending an email
When sending text messages
When APP pushes the news
For a lot of repetitive information, we can greatly reduce the amount of code written by formatting.
Let's think about the above scenarios when we are in the above scenarios. The contents of e-mails, text messages, news and other information you may receive are the same. But it is sent to many different people, here we only need to edit a unified content template, and then do the formatting operation, only need to format the recipient, so that different people can receive the same content.
Three ways of formatting according to the format of the type definition -% s
String formatting is implemented using operator%, example'my name is% s neo', my age is% s% ('neo', 18)'
Format character:% s
Connector: a% concatenation is used between the format string and the format variable, with a space on each side
Attachment: when we have only one variable in the string, we do not need to use tuples to wrap; when there is more than one, we need to use tuples to wrap.
Examples are as follows:
Info_01 ='My name is% s, age is% s'% ('Neo', 19) print (info_01) # > > My name is Neo, age is 19info_02 =' My name is% s, age is% s' name_01 = 'Neo'age_01 = 18name_02 =' Jack'age_02 = 17print (info_02% (name_01, age_01)) print (info_02% (name_02, age_02)) # > My name is Neo, age is pipes > > My name is Jack Age is 17 about Integer output
% o:oct octal
% d:dec decimal
X:hex hexadecimal
Print ("integers:% djas% dpas% d"% (1,2.2345)) print ("integers less than 5 digits, left blanks% 5d"% 11) print ("integers less than 5 digits, left padding 0d"% 11) print ("integers less than 5 digits Fill in the blanks on the right%-5d "% 11," end ") print (" octal% o "% 222) print (" hexadecimal% x "% 12)
The implementation results are as follows:
>
>
>
>
Octal 336
Hexadecimal c
Contains knowledge points:
When you have more than one parameter to format the output, you need to use tuples (1Magne2Pol 3); be careful not to use lists because lists are mutable
If a floating point number such as 2.2 is passed in, the final output is 2, which will only be rounded, not rounded.
If the string '2.2' is passed in, there will be an error!
About the output of floating-point numbers print ("floating-point numbers:% fjre% f"% (1,22.22)) print ("floating-point numbers retain two decimal places:% .2f"% 22.222) print ("floating-point numbers retain two decimal places with a width of 5 places, which is not enough to make up 0print .5f"% 2.222)
The implementation results are as follows:
# > > floating point number: 1.0000001 22.220000
# > > floating point number retains two decimal places: 22.22
The floating point number retains two decimal places with a width of 5 places, which is not enough to make up 02.22.
Contains knowledge points:
6 decimal places are retained by default. Decimal places can be specified in the form of .2f. 2 means to retain two decimal places.
About the output of the string print ("string:% Sforce% s% s"% (1,22.22, [1,2])) print ("string less than 5 digits, left blanks% 5s"%'2') print ("string less than 5 digits, right blanks%-5s"%'2s, "end") print ("string width 10 digits wide The result of intercepting two digits .2s "%" hello.world ") # is as follows: # > string: 1 he 22.22, [1] # > string less than 5 digits, left space 2 # > string less than 5 digits, right blank space 2 end# > string width 10 digits, intercept two digits of he
Contains knowledge points:
You can pass in any type of data, such as integers, floating-point numbers, lists, tuples, or even dictionaries, and it will be automatically converted to a string type.
String formatting function-format ()
Format () function formatting string is the most commonly used formatting method at present.
The string.format () function can also be used to format strings
The character body that uses the format () function uses {} curly braces instead of format characters
The usage is string.format (data, data, data...)
Without a number, that is, {}
With numeric number, the order can be changed, that is, {1}, {2}
With keywords, namely {a}, {b}
Examples are as follows:
Print ("today is {}, Neo", 18) print ("today is {0}, {1} {2} birthday party" .format ("January 1, 2020", "Neo", 18)) print ("today is {today}, {name} {age} birthday party" .format (today= "January 1, 2020", name= "Neo", age=18) Hight=) print ("Today is the {key} birthday party of {name}" He is trying {} ".format (" drinking ", name=" Neo ", key=18)) # print (" Today is {0} {} birthday party ".format (" Neo ", 18)) # print (" Today is {name} {key} birthday party ") He is trying {} ".format (name=" Neo ", key=18," drinking ") # the executive structure is as follows: # > > Today is January 1, 2020, Neo's 18th birthday party # > Today is January 1, 2020, Neo's 18th birthday party # > Today is January 1, 2020, Neo's 18th birthday party # > > Today is Neo's 18th birthday party, and he is trying to drink.
It should be noted that:
When you only write {}, it is read by default in the order of the values passed in.
When you write the number {1}, you can read the value in the corresponding position, starting with 0.
When you specify the keyword {name}, if you do not specify name=xxx, an error will be reported
When you specify a keyword and only write {}, the value specified with the keyword must be written at the end, similar to a function (formal parameter comes first, argument comes after)
{} and {1} cannot coexist.
Summary of format () function
When using format, the formatted output in a string is only in one way. Do not mix it. It is prone to problems and unnecessary.
Format () function-specifies the data type output print ("integer {: d}" .format (123)) print ("floating point number {: 5.2f}" .format (123.19)) print ("string {: s}" .format ('123')) print ("octal {: o}" .format (12)) print ("hexadecimal {: X}" .format (13)) # the execution result is as follows # > > floating point 123.numbers > > string 123s > octal numbers > hexadecimal d
Knowledge point
If: s is specified, only string values can be passed. If other types of values are passed, they will not be converted automatically.
When you do not specify a type, you can pass any type successfully. If there is no special need, you do not have to specify a type.
If you want to combine numeric numbering and keywords, you can use the following
Print ("keyword {num:d}" .format (num=123)) print ("Numeric number {0num=123 d}, {1print}" .format (123,123 ") # the execution result is as follows: # > keyword 123i > > Numeric 123123format () function-digit completion print ('default left alignment, width 10, insufficient blanks: {: 10}' .format (" 123"), "end") print ('left aligned, width 10) Insufficient blanks: {: 10} '.format ("start", "123") print (' right aligned, width 10, take two decimal places, insufficient 0: {: 0 > 10.2f} '.format (22.22555)) # the result is as follows: # > > default left alignment, width 10, insufficient blanks: 123FG > left alignment, width 10, insufficient spaces: 123FG > > right alignment, width 10 Insufficient blanks: start 12 spaces > right alignment, width 10, take two decimal places, insufficient complement 00000022.23
Knowledge point
The default left alignment can be added without adding > > always displays the symbol: 000cm 3.14000-3.1cm > percentage: 42.857143% 42.86% # > comma separated, which is generally used in money 12345678.
Knowledge dian
The meaning of + is that we can see symbols when we output positive numbers.
The percentage is a true percentage, not just adding a%; for example, 0.25667, if it becomes a percentage, it is 25.67%.
Fixed interval of three digits; an error will be reported in the incoming string
New formatting method: f-strings
First, you need to define a variable.
Precede the body of a string with an f symbol
Use {variable name} where you need to format
Examples are as follows:
Name = "Neo" age = 18message = f "Hello, {name}" print (message + "!") info = f "my name is {name}, and age is {age}" print (info + ".") # the execution result is as follows: # > > Hello.Neoclinic # > > my name is Neo, and age is 18. This is the end of the article on "how to format Python strings". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to format Python strings". If you want to learn more, you are welcome to follow the industry information channel.
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.