Python common functions

Source: Internet
Author: User

http://blog.csdn.net/pipisorry/article/details/45771045

Python built-in functions

Enumeration function Enumerate

>>> List (Enumerate (' abc '))

[(0, ' a '), (1, ' B '), (2, ' C ')]

The enumerate function can also receive a second parameter.

>>> List (Enumerate (' abc ', 1))

[(1, ' a '), (2, ' B '), (3, ' C ')]


Simple server

Do you want to quickly and easily share files in a directory?

# python2python-m simplehttpserver# Python 3python3-m http.server

This will cause a server to start.


Evaluate a Python expression

We all know the Eval function, but do we know the Literal_eval function?

Import AST

My_list = Ast.literal_eval (expr)

To replace the following actions:

expr = "[1, 2, 3]"

My_list = eval (expr)



Object Self-Test

In Python you can check the object using the Dir () function. As the following example:

>>> foo = [1, 2, 3, 4]

>>> dir (foo)

[' __add__ ', ' __class__ ', ' __contains__ ',

' __delattr__ ', ' __delitem__ ', ' __delslice__ ', ...,

' Extend ', ' index ', ' Insert ', ' pop ', ' Remove ',

' Reverse ', ' sort ']




Ternary operations

A ternary operation is a shortcut to a If-else statement, also known as a conditional operation. Here are a few examples that you can use to make your code more compact and aesthetically pleasing.

[On_true] if [expression] else [on_false]

X, y = 50, 25

small = x if x < y else y

from:http://blog.csdn.net/pipisorry/article/details/45771045

Ref:nifty Python Tricks


Python common functions

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.