Common python Functions

Source: Internet
Author: User

Common python Functions

 

Python built-in functions

Enumerate

 

>>> List (enumerate ('abc '))

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

 

The enumerate function can also receive the second parameter.

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

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


Simple Server

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

 
 

# Python2 python-m SimpleHTTPServer # Python 3 python3-m http. server

This will start a server.

 

Evaluate a Python expression

We all know eval functions, but do we know literal_eval functions?

Import ast

My_list = ast. literal_eval (expr)

To replace the following operations:

Expr = [1, 2, 3]

My_list = eval (expr)



Object self-check

In Python, you can use the dir () function to check objects. As shown in the following example:

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

>>> Dir (foo)

['_ Add _', '_ class _', '_ ins INS __',

'_ Delattr _', '_ delitem _', '_ delslice __',...,

'Extend', 'index', 'insert', 'pop', 'delete ',

'Reverse', 'sort ']



 

Ternary Computation

Ternary operations are quick operations for if-else statements, also known as conditional operations. Here are a few examples for your reference. They can make your code more compact and more beautiful.

[On_true] if [expression] else [on_false]

X, y = 50, 25

Small = x if x <y else y

 

 

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.