In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to keep the curly braces correctly". Friends who are interested might as well take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to keep the braces correctly.
Since Python 3.6.The f expression (f-string) has been introduced, which allows Python to do some simple calculations when populating strings. And the f expression is many times faster than the string .format method.
Whether it's an f expression or the .format method of a string, we can use curly braces as placeholders to populate the data. For example:
> > name = 'kingname' > print (my name is: {name}') my name is: kingname > print (the result of fission 1 is: {1: 1}') the result of 1: 1 is: 2 > salary= 999999 > print ('my monthly salary is: {salary} '.format (salary=salary)) my monthly salary is: 999999
But now the question is, what if I want to keep the curly braces while filling the content with an f expression or a .format method?
For example, when writing a crawler, I need to use a regular expression to extract the current number of pages from the current URL: page=\ d {0jue 3}. However, the name of this parameter indicating the number of pages may be different for different sites, some are page=xxx, some are Pag=xxx, some are pageNo=xxx, and some are p=xxx. So I want to generate this regular expression dynamically.
If we directly use the f expression or the .format method, we will report an error:
> page_name= 'page' > page_regex_template =' {page_name} =\ d {0in KeyError 3}'> print (page_regex_template.format (page_name=page_name)) Traceback (most recent call last): File ", line 1, in KeyError: '0Lind 3'
In order to generate regular expressions properly, one might think of using the old% s placeholder:
> page_name = 'page' > page_regex_template ='% s =\ d {0 3}'> print (page_regex_template% page_name) page=\ d {0 3}
Although it is feasible, mixing the two methods of populating strings makes the code difficult to maintain, and placeholders such as% s are very slow to fill.
In fact, in Python's f expressions and .format methods, if you need to keep the curly braces, you just need to write them in the form of curly braces:
> page_name= 'page' > page_regex_template =' {page_name} =\ d {{0page_name 3}}'> print (page_regex_template.format (page_name=page_name)) page=\ d {0Magne3}
The first braces inside the curly braces automatically invalidate and become ordinary characters. However, if it is braces, the innermost pair of braces will continue to act as placeholders, for example:
> page_name= 'page' > page_range=' 0page_range=page_range 5'> page_regex_template ='{page_name} =\ d {page_range}'> print (page_regex_template.format (page_name=page_name, page_range=page_range)) page=\ d
To sum up, if you count from the outside to the inside, if the outermost curly braces are called layer 1, then the odd braces are used to populate the data, and the even braces are ordinary characters. Therefore, if we do not consider the readability of the code, if we need the resulting string itself to be in the form of nested curly braces, we can further write:
> > ugly_string ='2 layer nested braces: {variable}'> > print (ugly_string.format (variable=variable)) layer 2 nested braces: {{name}} > > ugly_string ='3 layer nested braces: {variable}'> > print (ugly_string.format (variable=variable)) layer 3 nested braces: {name}
Suppose we want to retain n-layer braces in the final output string, then in the code, we need to write 2n + 1 layers of braces. As you can see, if you want to write like this, you will have to count your glasses by counting the number of curly braces. Therefore, in the actual development, the number of layers of curly braces should never exceed 2.
The following content is for students who have spare time to read.
The method mentioned above is applicable to the case of pairs of curly braces, if there is only half of the curly braces, for example, the text information of some websites is written in the source code in JSON format, then we can use regular expressions to extract the JSON containing the text and then further deal with it. In general, the regular expression may be like this: content= (\ {);. However, some sites use the word content, others use detail, so this place needs to be filled in. If we write as usual, we will still report an error, for example:
> content_name= 'detail' > content_json_template =' {content_name} = ({\ {}) $'> print (content_json_template.format (content_name=content_name)) Traceback (most recent call last): File ", line 1, in ValueError: unexpected'{'in field name
One layer doesn't work, so let's see how about two layers:
> content_name= 'detail' > content_json_template =' {content_name} = ({{\ {}}) $'> print (content_json_template.format (content_name=content_name)) Traceback (most recent call last): File ", line 1, in IndexError: Replacement index 0 out of range for positional args tuple
It's still wrong to set two layers.
If the string does not contain a backslash, we can use an f expression with quotation marks to enclose half of the curly braces, for example:
> name = 'kingname' > > print (f' my name is: {name}, my parameter is: {"{"}') my name is: kingname, my parameter is: {
But the problem is that backslashes are not allowed in the f expression, otherwise an error will be reported:
> content_name = 'detail' > content_regex = f' {content_name} = ({\ "{"}) $'File ", line 1 SyntaxError: f-string expression part cannot include a backslash
The .format method supports backslashes, but it does not support the way quotation marks enclose one-sided curly braces:
> > name= 'kingname' > > print (' my name is: {name}, my parameter is: {"{"} '.format (name=name)) Traceback (most recent call last): File ", line 1, in ValueError: unexpected' {'in field name
In such a situation, how should we solve it? As long as you open your mind and be flexible, you can find many ways. Here are just two examples:
Put curly braces in the value
Adjust the train of thought. Since curly braces can't be put in the sentence template, let's put them in the populated value:
# use the .format method > > name= 'kingname' > brace=' > > print ('my name is: {name}, my parameter is: {brace} '.format (name=name, brace=brace)) my name is: kingname, my parameter is: {# use f expression > > content_name =' detail' > brace='\ {'> > print (f'{content_name} = ({brace}) $') detail= (\ {) $
Don't forget string concatenation
One of the most common problems is that when you learn something new, you forget the old one. In fact, string concatenation can also solve the problem:
> content_name = 'detail' > content_json = content_name +' = (\ {) $'> print (content_json) detail= (\ {) $so far, I believe you have a deeper understanding of "how to correctly retain curly braces". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.