Python tips and related errors

Source: Internet
Author: User
Tags eol

File:

Open the file, if the error prompt GBK, may be the file content encoding problem, can be opened with parameters:
Open (Filename=path,encoding=none)

-------------------------------------------------------------------------------------------
Sequence:

Lists, tuples, and dictionaries can be indexed to get values, lists and tuples get indexed values, and dictionaries get key.
Dict1.setdefault (x, y)------Append to Dictionary

The following two sentences have the same meaning and return the same result:
For I in Dict1
For I in Dict1.keys ()

--------------------------------------------------------------------------------------------
Character:

Methods of characters
Str.splitext ()-----Split by the following parameters
such as A= ' 1:2 '
A.splitext (': ') gets a tuple


\ nthe line break
\b Backspace
\a emits system ring tones


\ t Transverse tab
\v Portrait tab
\ r Enter
\f Page Change
\o octal
\x Hex
\ = a Space
\ \ counter Slash


character action method:
isalpha () determine if character is
isdigit () determines whether the number
upper () is converted to uppercase
lower () converted to lowercase
capitalize () string first letter uppercase
title () capitalize the first character of the first uppercase space or punctuation

spilt () available parameters for slicing operations
example: 2:3
a,b = Spilt (2:3)
a
2
b
3


>>> str1
' ***skdfj*** '
>>> str1 = Str1.strip ()
' ***skdfj*** '
>>> str1 = Str1.strip (' * ')
' SKDFJ '
Lstrip () Delete the left space or character
Rstrip () Delete the right space or character

Count () Statistics string occurrences
Find () finds where the string appears
Replace () Replacement string


--------------------------------------------------------------------------------------------
Error:

Enter the content below only if the condition is wrong
Try
Conditions:
Except
Input content
You can use raise in try to return an incorrect name and execute the following except statement

The raise error name can produce an error name, and this name python must exist
Raise Keyboardinterrupt

---------------------------------------------------------------------------------------------
Formatting:

There are two ways to format the decimal place:----you must add a small point before 2f, otherwise the wrong value will be returned.
A = 3.1415926
Print (' This is {0:.2f} '. Format (a))
Print (' This is%.2f '% a)

>>> numbers = [10,30,3,0,100]
>>> for number in numbers:
if number = = 0:
print (' This is 0, cannot be removed, otherwise it will be wrong ')
newnum = 100/number
Span style= "font-size:12px" >print ((' 100/{} = {}). Format (number,newnum))

syntaxerror:eol while scanning string literal
>>> for number in numbers:
if Number = = 0:
print (' This is 0, cannot be removed, otherwise error ')
newnum = 100/number
print ((' 100/{} = {} '). Format (number,newnum))

100/10 = 10.0
100/30 = 3.3333333333333335
100/3 = 33.333333333333336
this is 0, cannot be removed, otherwise error
traceback (most recent call last):
File" <pyshell#59> ", line 4, in <module>
Newnum = 100/number
zerodivisionerror:division by zero
>>> for number in numbers:
if number = = 0:
print (' This is 0, cannot be removed, otherwise it will be wrong ')
continue
newnum = 100/number
print (' 100 /{} = {} '). Format (number,newnum))

100/10 = 10.0
100/30 = 3.3333333333333335
100/3 = 33.333333333333336
This is 0, cannot be removed, otherwise it will be wrong
100/100 = 1.0
>>>


------------------------------------------------------------------------------------------------
Function:

The main () function of lesson 16
The list of reverse () returns is none,reversed (list) that can be returned normally


Locals ()---refers to the current directory

List normal through pop is the last one that pops up, and if you want to use FIFO, the following functions are available:
From collections Import Deque
Deque.left () pops up the left-most

-------------------------------------------------------------------------------------------------
35 Lessons Easygui Summary

Button:
MsgBox ()-----message Dialog, return button value
Ccbox () Ynbox ()-------button 1 returns 1, button 2 returns 0
Buttonbox ()-----Multiple buttons, return button name values
Indexbox ()-------button 1 returns 0, button 2 returns 1
Bootbox ()---------------button 1 returns 1, button 2 returns 0


Options:
Choicebox ()--------single selection
Multchoicebox ()------Multiple selection

Message input:
Enterbox ()-------message input, returns the input information
Integetbox ()-------digital input, non-digital re-entry
Multenterbox ()-------Multiple message inputs and returns a list

Password Input:
PasswordBox ()------password input, return password string
Multpasswordbox ()------Multiple inputs, the last one showing asterisks
TextBox ()

Catalog Files:
Diropenbox ()-------directory open, display directory path
Fileopenbox ()---------file opens, showing file path
Filesavebox ()---------file save, show file path

Catching Exceptions:
Exceptionbox ()----------catch exception information, return to window

-----------------------------------------------------------------------------------------------
Module Chardet

Encoding for detecting the target Web page

Can be installed by Easy_install or PIP mode
Cmd:easy_install Chardet

Chardet.detect (HTML)----Get a dictionary where the HTML must have been read
Chardet.detect (Res.read ())
{' Encoding ': ' GB2312 ', ' confidence ': 0.99}

The encoding can be obtained by means of key:
>>> (Chardet.detect (Res.read ())) [' Encoding ']
' GB2312 '


-----------------------------------------------------------------------------------------------
Module Shutil

For file operations, moving

Directory Operations:
Os.mkdir ("file")
Create a Directory

To copy a file:
Shutil.copyfile ("Oldfile", "NewFile")
Oldfile and NewFile can only be files.

Shutil.copy ("Oldfile", "NewFile")
Oldfile can only be a folder, NewFile may be a file, or it can be a destination directory

To copy a folder:
Shutil.copytree ("Olddir", "Newdir")
Olddir and Newdir can only be directories, and newdir must not exist

Renaming files (directories)
Os.rename ("Oldname", "NewName")
The file or directory is used by this command

Moving Files (directories)
Shutil.move ("Oldpos", "Newpos")
Oldpos can be a file
Newpos is the directory

deleting files
Os.remove ("file")

Delete Directory
Os.rmdir ("dir") can only delete empty directories

Shutil.rmtree ("dir")
Empty directories, contents of the directory can be deleted

Converting catalogs
Os.chdir ("path") Change path


The OS module calls the system shell in the following ways:
Os.system (CMD)
Os.popen (CMD)
You can also use the Subprocess module
Subprocess.call (CMD)

-----------------------------------------------------------------------------------------------
Module Urllib.request

You can download the image using the following command
Urllib.request.urlretrieve (Each,filename,none)

Get all the Img_url in the subgroup by FindAll, is a list
p = R ' src= "([^"]+\.jpg) '
Mglist = Re.findall (p,html)

Open each URL in an iterative way
For each in Get_url ():
Separate the file with the split method of the string, taking the last
filename = each.split ('/') [-1]
Download with Urlretrieve, no more open a file write
Urllib.request.urlretrieve (Each,filename,none)

Lists, tuples, and dictionaries can be indexed to get values, lists and tuples get indexed values, and dictionaries get key.

Dict1.setdefault (x, y)------Append to Dictionary

Methods of characters
Str.splitext ()-----Split by the following parameters
such as A= ' 1:2 '
A.splitext (': ') gets a tuple

You can use raise in try to return an incorrect name and execute the following except statement

There are two ways to format the decimal place:----you must add a small point before 2f, otherwise the wrong value will be returned.
A = 3.1415926
Print (' This is {0:.2f} '. Format (a))
Print (' This is%.2f '% a)


\ nthe line break
\b Backspace
\a emits system ring tones


\ t Transverse tab
\v Portrait tab
\ r Enter
\f Page Change
\o octal
\x Hex
\ = a Space
\ \ counter Slash

For

>>> numbers = [10,30,3,0,100]
>>> for number in numbers:
if number = = 0:
print (' This is 0, cannot be removed, otherwise it will be wrong ')
newnum = 100/number
Span style= "font-size:12px" >print ((' 100/{} = {}). Format (number,newnum))

syntaxerror:eol while scanning string literal
>>> for number in numbers:
if Number = = 0:
print (' This is 0, cannot be removed, otherwise error ')
newnum = 100/number
print ((' 100/{} = {} '). Format (number,newnum))

100/10 = 10.0
100/30 = 3.3333333333333335
100/3 = 33.333333333333336
this is 0, cannot be removed, otherwise error
traceback (most recent call last):
File" <pyshell#59> ", line 4, in <module>
Newnum = 100/number
zerodivisionerror:division by zero
>>> for number in numbers:
if number = = 0:
print (' This is 0, cannot be removed, otherwise it will be wrong ')
continue
newnum = 100/number
print (' 100 /{} = {} '). Format (number,newnum))

100/10 = 10.0
100/30 = 3.3333333333333335
100/3 = 33.333333333333336
This is 0, cannot be removed, otherwise it will be wrong
100/100 = 1.0
>>>

Output: Year-month-day
Date1 = Time.strftime ('%y-%m-%d ')

Output: Hours: minutes: seconds
time1 = Time.strftime ('%h:%m:%s ')

Install this type of file
Install PIP install Wheel First
Then use PIP install XXX.WHL
Django-1.9.8-py2.py3-none-any.whl

Python3 version does not support MySQL, available pymyql, but in the Django Sync database, you need to add the following in the app __init__.py:
Import Pymysql
Pymysql.install_as_mysqldb ()

Python tips and related errors

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.