您的位置:首页 > 编程语言 > Python开发

Python2.7 学习笔记 (一)——基础知识

2012-03-07 18:07 781 查看
2012-3-7

#使用版本:Python 2.7.2

当行注释 #

多行注释 ''' 或者 """ (三个单引号或者双引号)

当行多断代码隔离 ;

下段代码的开始 :

代码的连接 print "too long"\

" words"\

相当于 print too long words

1. 类型转换

int(string)

float(String)

chr(ASCII值到字符)

ord(ASCII字符转换成值)

oct(String) 八进制

hex 16进制

long 长整型

String.atoi(num) #字符串->int

2.基本输入

name = raw_input('please input your name')

3.使用中文

第一行: #-*-coding:utf-8-*-

String.decode('utf-8')

String.encode('gbk')

4.数学计算

import math

math.sin(60)

math.pi

math.sqrt(9) #3

math.log10(100) #2

math.pow(2,8) #256

5.运算符

+ - * / 加减乘除

** 乘方

| ^ & 按位或 ,异或, 与

<< >> 左移运算,右移运算

6.转义符

\n 换行

\t 制表

\r 回车

\\ \' \" # \ ,' , "

7.字符串

string.capitalize()

string.count() #获得某一子字符串的数目

isidgit ,isalpha ,islower,istitle(),join,lower ,split ,len(string)

String[0] #字符串第一个字符

String[-1] #字符串最后一个字符

String[-2] #字符串倒数第二个字符

String[0:-2] #从第一个字符,到倒数第二个字符,但是不包含倒数第二个字符

8.格式化输出

%c %d %o %s

%x %X(十六进制整数,其中字母大写)

str = 'so %s day'

print str % 'beautiful'

9.原始字符串(Raw String)

以R或r 开头的字符串,没有转义字符

import os

path =r'c:\test' #这里\t就不是制表符的意思了

dirs =os.listdir(path)

print dirs

10.列表 list

list=[]

list.append(1)

list.count(2) #2在list里出现的次数

list.extend([2,3,4,5])

list.inedx(5)

list.insert(2,6)

list.pop(2) #弹出index是2的数

list.remove(5)#移除5个数字

list.reverse()

list.sort()

list[1:4] #返回下标1到3的数字(不包含4)

list[1:-1] #返回第二个到最后一个的数,但不包含最后一个

11.字典 Dictionary

键值对 key:value

dic={'apple':2 ,'orange':1}

dic.clear()

dic.copy()

dic.get(key)

dic.has_key(key)

dic.items()

dic.keys()

dic.values()

dic.pop(k) #删除k

dic.update()

12.文件File

open(filename,mode,bufsize) #mode: r(读方式),w(写方式) ,b(二进制)

file.read() #读入文件到字符串

file.readline() #读取一行

file.readlines()#读取所有行

file.write() #字符串写到文件

file.writelines()#列表写到文件

#open file as write mode

file = open('c:/Python27/test/hello.py','w')

file.write('print "write python"\n')

#generate list and write into file

list=[]

for i in range(10)

s=str(i)+'\n'

list.append(s)

file.writelines(list)

file.close()

#print out the file content

file = open('c:/Python27/test/hello.py','r')

s = file.read()

print s

12.if 语句

if :

else if:

else :

13.for 语句

for <str> in <list>:

if<condition> :

break

if<condition> :

continue

else:

print

14.range

range(start,stop,step) #start,step可选参数

for i in range(1,5+1,1) # 打印 1-5 ,步长为1

print i

15.while

while<condition>:

do loop

复制搜索

复制搜索
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: