Tips and tips for python

Source: Internet
Author: User

From http://www.2cto.com/kf/201105/92200.html

How to determine the operating system type

Import sys
Print sys. Platform
Print sys. Version
Display and modify the module search path of Python

>>> Import sys
>>> Print sys. Path
[,/Usr/lib/python23.zip,/usr/lib/python2.3,/usr/lib/python2.3/plat-linux2,
/Usr/lib/python2.3/lib-TK,/usr/lib/python2.3/lib-dynload,/usr/local/lib/python2.3/Site-packages,
/Usr/lib/python2.3/Site-packages]
>>> SYS. Path. append (/usr/lib/mypath)
>>> Print sys. Path
[,/Usr/lib/python23.zip,/usr/lib/python2.3,/usr/lib/python2.3/plat-linux2,
/Usr/lib/python2.3/lib-TK,/usr/lib/python2.3/lib-dynload,/usr/local/lib/python2.3/Site-packages,
/Usr/lib/python2.3/Site-packages,/usr/lib/mypath]
Converts a list to a string.

>>> T = [a, B, c]
>>> Print T
[A, B, c]
>>> Import string
>>> Print string. Join (t)
A B C
Operating SystemProgram

>>> Import OS
>>> OS. System (LS) # Use OS. System () to execute system commands
>>> EXEC "OS. System (LS)" # execute the commands in the string using exec. The two commands have the same effect.
The output of the preceding two commands is directly displayed on the screen and cannot be saved to variables. If we want to save the output, we can use the OS. Pope N () function.

>>> Cmd =/usr/bin/mkntpwd % S % Password
>>> Handler = OS. popen (CMD, R)
>>> Passwordstring = handler. Read () # passwordstring is the output result of the mkntpwd program.
The commands module can also be used to obtain program output. the popen () Encapsulation function enables us to more easily obtain the running system commands and obtain the command output. However, this module is only valid on UNIX systems and cannot be used on Windows platforms.

>>> Import commands
>>> Status, output = commands. getstatusoutput (LS-l)
>>> Print Output
Total 96564
-RW-r -- 1 Root 4459 2005.sxw
-RW-r -- 1 Root 27511 20060412_user.ods
-RW-r -- 1 Root 202258 January scenery-.jpg
...
>>> Print status
0
Introduce a new module named subprocess in python2.4 to replace OS. System, OS. Spawn *, OS. popen *, popen2. *, and commands .*.

Encoding conversion

#! /Usr/bin/Python
#-*-Coding: UTF-8 -*-

A = u "test"
B =. encode (gb2312)
Print a
Print B
A = China
. encode (gb2312)
traceback (most recent call last):
file " ", line 1, in?
file "/usr/lib/python2.3/encodings/gb2312.py", line 21, in encode
If C unicodedecodeerror: ASCII codec cant decode byte 0xe4 in position 0: ordinal not in range (128)
>> Unicode (A, UTF-8)
uu4e2du56fd
B = Unicode (A, UTF-8)
Print B
China
C = B. encode (gb2312)
C
xd6xd0xb9xfa
Print C # C is the 'China' of the gb2312 character set ', it is normal to display garbled characters in my UTF-8 system.
?
PS: My shell environment is UTF-8.
exchange two variables

>>> A, B = 1, 2
>>> A, B
(1, 2)
>>> A, B = B,
>>> A, B
(2, 1)
>>>
2
>>> B
1
Test Data Type

>>> A = 123
>>> B = test
>>>
123
>>> B
Test
>>> Isinstance (A, INT)
True
>>> Isinstance (A, STR)
False
>>> Isinstance (B, INT)
False
>>> Isinstance (B, STR)
True
Use in to determine whether the Sub-string is included

>>> A = This is my test
>>> Is in
True
>>> Mm in
False
_ ITER _ iterator

>>> A = "iterator"
>>> T = ITER ()
>>> T. Next ()
I
>>> T. Next ()
T
>>> T. Next ()
E
>>> T. Next ()
R
>>> T. Next ()
A
>>> T. Next ()
T
>>> T. Next ()
O
>>> T. Next ()
R
>>> T. Next ()
Traceback (most recent call last ):
File "<stdin>", line 1, in?
Stopiteration
Write an iterator class by yourself

>>> Class reverse:
... Def _ init _ (self, data ):
... Self. Data = Data
... Self. Index = Len (data)
... Def _ ITER _ (Self ):
... Return self
... Def next (Self ):
... If self. Index = 0:
... Raise stopiteration
... Self. Index = self. Index-1
... Return self. Data [self. Index]
...
>>> For char in reverse (iterator ):
... Print char
...
R
O
T
A
R
E
T
I
>>>
Through getattr, we can get a reference of an object that knows the specific function name at runtime, which can enhance the flexibility of our program.

>>> Li = [a, B]
>>> Getattr (Li, append)
>>> Getattr (Li, append) (c) # equivalent to Li. append (c)
>>> Li
[A, B, c]
>>> Handler = getattr (Li, append, none)
>>> Handler
<Built-in method append of list object at 0xb7d4a52c>
>>> Handler (CC) # equivalent to Li. append (cc)
>>> Li
[A, B, c, CC]
>>> Result = handler (bb)
>>> Li
[A, B, c, CC, BB]
>>> Print result
None
Programming example:

Import statsout

Def output (data, format = "text "):
Output_function = getattr (statsout, "output _ % s" % format)
Return output_function (data)
AboveCodeThe output function receives a data parameter and a format parameter. According to the value of the format parameter, the output_text function is taken from the statsout module to run. The data parameter is run through output_function (data) passed to the output_text function in the statsout module. You can extract different function operations (output_xxxx) from the statsout module by using different formats ). That is to say, the function we want to run is determined after the program runs. In this way, different functions can be named in the form of output_xxx in the statout module, and various functions can be dynamically called through the above program.

Hasattr is used to determine whether an object has an attribute.

Syntax:
Hasattr (object, name)-> bool
Checks whether the object has the name attribute and returns a Boolean value.
Split Sequence

>>> A = [C for C in abcdefg]
>>>
[A, B, c, d, e, f, g]
>>>
Split sequence by if condition

>>> A = [C for C in 123456 if int (c) <3] If the if condition is true, the for loop is executed.
>>>
[1, 2]
>>> A = [C for C in 123456 if int (c)> 3] If the if condition is false, the for loop is not executed.
>>>
[4, 5, 6]

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.