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

Python基本语法1

2013-05-02 15:07 363 查看
2012-3-7#使用版本:Python 2.7.2当行注释 # 多行注释 ''' 或者 """ (三个单引号或者双引号)当行多断代码隔离 ; 下段代码的开始 : 代码的连接 print "too long"\ " words"\ 相当于 print too long words1. 类型转换 int(string) float(String)chr(ASCII值到字符) ord(ASCII字符转换成值)oct(String) 八进制hex 16进制long 长整型String.atoi(num) #字符串->int2.基本输入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.pimath.sqrt(9) #3math.log10(100) #2math.pow(2,8) #2565.运算符+ - * / 加减乘除** 乘方| ^ & 按位或 ,异或, 与 << >> 左移运算,右移运算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 dirs10.列表 listlist=[]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:valuedic={'apple':2 ,'orange':1}dic.clear()dic.copy()dic.get(key)dic.has_key(key)dic.items()dic.keys()dic.values()dic.pop(k)
#删除kdic.update()12.文件Fileopen(filename,mode,bufsize) #mode: r(读方式),w(写方式) ,b(二进制)file.read() #读入文件到字符串file.readline() #读取一行file.readlines()#读取所有行file.write() #字符串写到文件file.writelines()#列表写到文件#open file as write modefile = open('c:/Python27/test/hello.py','w')file.write('print
"write python"\n')#generate list and write into filelist=[]for i in range(10)s=str(i)+'\n'list.append(s)file.writelines(list)file.close()#print out the file contentfile = open('c:/Python27/test/hello.py','r')s = file.read()print s 12.if 语句 if :else if:else
:13.for 语句for in :if : breakif : continueelse: print14.rangerange(start,stop,step) #start,step可选参数for i in range(1,5+1,1) # 打印 1-5 ,步长为1print i15.while while:do loop
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: