Some of the most obscure basic tricks of Python

Source: Internet
Author: User

The 1.startswith () and endswith () parameters can be tuples

When detecting the beginning or end of a string, if you have more than one detection value, you can use the tuple as startswith() the and endswith() parameter:

1 # Bad2 ifImage.endswith ('. jpg')orImage.endswith ('. PNG')orImage.endswith ('. gif'):3     Pass4 #Good5 ifImage.endswith (('. jpg','. PNG','. gif')):6     Pass7 # Bad8 ifUrl.startswith ('http:')orUrl.startswith ('https:')orUrl.startswith ('ftp:'):9     PassTen #Good One ifUrl.startswith (('http:','https:','ftp:')): A     Pass
2.enumerate () set start parameter as index start value

When using enumerate () iteration to get an index at the same time, you can set the start parameter as the index starting value:

1 #  Bad 2  for inch Enumerate (data): 3     Print (Index+1, v) 4 # Good 5  for  in enumerate (data, start=1):6     print(index, v)

3. Name the slice

When hard-coded tile indexes are everywhere in your code, our code becomes inaccessible. You can name the slice to resolve this issue:

1 ' .................... 100.................513.25.'2#  bad3 cost = Int (record[20:23 ]) * FLOAT (record[40:46])4#  good5 SHARES = Slice  6 Price = Slice (+7 )cost = Int (Record[shares]) * FLOAT (Record[price])

As a basic guideline, there are many hard-coded index values in the code that will result in poor readability and maintainability. In general, the built-in slice () function creates a slice object that can be used wherever a slice is allowed. For example:

1>>> items = [0, 1, 2, 3, 4, 5, 6]2>>> a = Slice (2, 4)3>>> Items[2:4]4[2, 3]5>>>Items[a]6[2, 3]7>>> Items[a] = [-2,-3]8>>>Items9[0, 1,-2,-3, 4, 5, 6]Ten>>>delItems[a] One>>>Items A[0, 1, 4, 5, 6] ->>>

Python Learning Exchange Group: 125240963

4. Context Manager can manage multiple resources at the same time

Suppose you want to read the contents of a file, and after processing it, write to another file. You can write pythonic code, so you use the context Manager and write the following code satisfactorily:

1 with open ('input.txt'R') as Source:  2with     open ('output.txt'w') as Target:3         target.write (Source.read ())

You've done a great job, but the context manager can manage multiple resources at the same time, and this code can also be written like this:

1 with open ('input.txt'R') as source, open ('  output.txt"w") as target:2     Target.write (Source.read ())
5.else clause

The ELSE clause in Python can be used not only in the IF statement, but also in the for, while, and try statements.
The else block is run when the for loop or while loop is complete (rather than through a break statement or a return statement or an exception exit loop).
As an example:

1>>> forIinchRange (3):2...Print(i)3...Else:4...Print('iterated over everything')5 ... 6 071829 iterated over everythingTen>>>

As above, the For loop ends normally, so the subsequent else block is run.

1>>> forIinchRange (3):2...ifi = = 2:3... Break4...Print(i)5...Else:6...Print('iterated over everything')7 ... 8 091Ten>>>

As you can see, if the For loop is not running properly (as above is the break end loop), the subsequent else block will not run.

The Else block is run only if no exception is thrown in the try block. At first, you may not feel the need to use the ELSE clause in a try/except block. After all, in the code snippet below, only Dangerous_call () does not throw an exception, After_call () will execute, right?

1 Try : 2     dangerous_call ()3    after_call ()4except  oserror:  5     log ('oserror ... ')

However, After_call () should not be placed in a try block. For clarity, the try block should include only the statements that throw the expected exception. Therefore, it is better to write to the following:

1 Try : 2     dangerous_call ()3except  oserror:4     log ('  OSError ... ' )5Else:6     After_call ()

It is now clear that the try block is Dangerous_call () possible error, not After_call (). It is also clear that After_call () is executed only if the try block does not throw an exception. Note, however, that the exception thrown by the ELSE clause is not handled by the preceding except clause, which means that after_call () will not be caught if it throws an exception at this point.

Python Learning Exchange Group: 125240963

Reprint to: Http://www.revotu.com/python-some-common-tricks.html#more

Some of the most obscure basic tricks of Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.