python 入门

http://www.jb51.net/article/926.htm
http://freshventure.wordpress.com/2011/02/23/%E5%88%A9%E7%94%A8python%E5%B0%86csv%E6%96%87%E4%BB%B6%E5%AF%BC%E5%85%A5mysql/
1、中文显示


print "Hello,world!"

print "欢迎来到奥运中国!"


##raw_input("Press enter key to close this window");

a=100.0
b=201.1
c=2343

print (a+b+c)/c


print """

Usage:thingy[OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""


word="abcdefg"
a=word[2]
print "a is : " + a
b=word[1:3]
print "b is: " +b # index 1 and 2 elements of word.
c=word[:2]
print "c is: " +c #index 0 and 1 elements of word.
d=word[0:]
print "d is:" +d # All elements of world.

e=word[:2]+word[2:]
print "e is:" + e #All elements of word.

f=word[-1]
print "f is:" + f #All elements of word.

g=word[-4:-2]
print "g is:" + g

i=word[:-2]
print "i is:" +i
l=len(word)
print "Length of word is:" + str(l)



2、
[code="java"]
I'm sorry in unicode is:8
# vi python_test2.py

print "input your Chinese name:"

s=raw_input("Press enter to be continued");

print "Your name is :" + s;

l=len(s)
print "Length in asc codes is:" + str(l);

a=unicode(s,"GBK");
l=len(a)

print "I'm sorry in unicode is:" + str(l);
[/code]


python程序有问题:错误提示:IndentationError:expected an indented block!
块缩进前后用的不一样
要么都是空格,要么都是tab

#Multi-way decisioin

x=int(raw_input("Please enter an integer:"))

if x<0:

x=0

print "Negative changed to zero"

elif x==0:

print "Zero"

else:

print "More"

#Loops List
a=['cat','window','defenestrate']
for x in a:

print x, len(x)



3、文件操作


spath="/data/remote-log-server/log/gamelogin/wqo/test/baa.txt"

f=open(spath,"w")
f.write("First line 1.\n")
f.writelines("Second line 2.")

f.close()

f=open(spath,"r")

for line in f:

print line


f.close()

F.close()
#关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。如果一个文件在关闭后还对其进行操作会产生ValueError
F.flush()
#把缓冲区的内容写入硬盘
F.fileno()
#返回一个长整型的”文件标签“
F.isatty()
#文件是否是一个终端设备文件(unix系统中的)
F.tell()
#返回文件操作标记的当前位置,以文件的开头为原点
F.next()
#返回下一行,并将文件操作标记位移到下一行。把一个file用于for ... in file这样的语句时,就是调用next()函数来实现遍历的。
F.seek(offset[,whence])
#将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。

4、包引用

每一个.py文件称为一个module,module之间可以互相导入
假设我们有一个parent文件夹,该文件夹有一个child子文件夹.child中有一个module a.py

import sys
sys.path.append('D:\\download')

from parent.child.a import add_func


print sys.path

print "Import add_func from module a"
print "Result of 1 plus 2 is: "
print add_func(1,2)


5、使用cvs模块
逐行处理
for line in open("samples/sample.csv"):
title, year, director = line.split(",")
print year, title

使用csv模块
import csv
reader = csv.reader(open("samples/sample.csv"))
for title, year, director in reader:
print year, title


import csv

#从文件读取
reader = csv.reader(file(srcFilePath,'rb'))

for line in reader:
#忽略第一行
if reader.line_num == 1:
continue

#line是个list,取得所有需要的值
type = line[0]


#写入文件
writer = csv.writer(open(targetFile,"wb"),quoting=csv.QUOTE_ALL)

#传入list
writer.writerow(["121","121"])

#传入2纬list
writer.writerows([["121","121"]])




5、对象的方法:
对象的方法对象的方法是指绑定到对象的函数。调用对象方法的语法是instance.method(arguments)。它等价于调用Class.method(instance, arguments)。当定义对象方法时,必须显式地定义第一个参数为self,用于访问对象的内部数据。self相当于C++, Java里面的this变量。比如:

class Fish:
def eat(self, food):
if food is not None:
self.hungry=False

#构造Fish的实例:
f=Fish()
#以下两种调用形式是等价的:
Fish.eat(f, "earthworm")
f.eat("earthworm")
Python认识一些以”__“开始并以"__"结束的特殊方法名,它们用于实现运算符重载和实现多种特殊功能。


6、%的作用

print '变量a的值的十进制形式为%d' %a

做一个简单的解释。这个语句的含义是将变量a以有符号整数的形式输出。这里的百分号%是Python语言中的格式化运算符,它可以在字符串中插入一个变量值。格式化运算符左边是一个字符串,即下面用蓝色字体表示的部分:

print '变量a的值的十进制形式为%d' %a

格式化运算符左边的字符串中可以含有一个或多个转换指示符,本例中只有一个转换指示符,即%d。就像这里看到的一样,转换指示符通常以百分号打头,后面紧跟一个字符串格式化字符,需要注意的是,转换指示符中的百分号是作为字符串格式化字符的前导符使用,而非格式化运算符。字符串格式化字符d表示将在当前字符串的指定位置放上一个整数。打印输出时,字符串中的转换指示符将被指定的值替换掉,所以转换指示符还起到占位符的作用。格式化运算符的右边,即上面用红色字体表示的部分,规定用谁来替换字符串中的占位符。就本例而言,我们要用变量a来替换字符串中的占位符%d。

与数值有关的字符串格式化字符及其作用如下所示:

 d: 有符号十进制整数
 u: 无符号十进制整数
 o: 无符号八进制整数
 x: 无符号十六进制整数,a~f采用小写形式
 X: 无符号十六进制整数,A~F采用大写形式
 f: 浮点数
 e,E: 浮点数,使用科学计数法
 g,G: 浮点数,使用最低有效数位


print "Error %d: %s" % (e.args[0], e.args[1])

前两个为占位符,第三个是替换的意思

-----------------------------------------

Python 中,字符串是“不可改变的序列”。尽管不能“按位置”修改字符串(如字节组),但程序可以引用字符串的元素或子序列,就象使用任何序列一样。Python 使用灵活的“分片”操作来引用子序列,字符片段的格式类似于电子表格中一定范围的行或列。

另一个功能强大的字符串操作就是简单的 in 关键字。

 
>>> for c in s[11:18]:
... print c
...
l
i
t
t
l
e



>>> if 'y' in s:
... print 'get y'
...
get y


在 Python 中,有几种方法可以构成字符串文字。可以使用单引号或双引号,只要左引号和右引号匹配,常用的还有其它引号的变化形式。如果字符串包含换行符或嵌入引号,三重引号可以很方便地定义这样的字符串,使用单引号或三重引号的字符串前面可以加一个字母 "r" 以表示 Python 不应该解释规则表达式特殊字符。

>>> s4 = r"this \n and \n that"
>>> print s4
this \n and \n that
>>>


文件对象提供了三个“读”方法: .read()、.readline() 和 .readlines()。每种方法可以接受一个变量以限制每次读取的数据量,但它们通常不使用变量。 .read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。然而 .read() 生成文件内容最直接的字符串表示,但对于连续的面向行的处理,它却是不必要的,并且如果文件大于可用内存,则不可能实现这种处理。

.readline() 和 .readlines() 非常相似。它们都在类似于以下的结构中使用:

.readline() 和 .readlines() 之间的差异是后者一次读取整个文件,象 .read() 一样。.readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for ... in ... 结构进行处理。另一方面,.readline() 每次只读取一行,通常比 .readlines() 慢得多。仅当没有足够内存可以一次读取整个文件时,才应该使用 .readline()。

import string

>>> import string
>>> string.whitespace
'\t\n\x0b\x0c\r '
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.find(s,'had')
5
>>> string.count(s,'a')
4
>>> string.split(s)
['mary', 'had', 'a', 'little', 'lamb']



标准模块:re 规则表达式

>>> import re
>>> s = "mary had a little lamb"
>>> if re.search("m", s):
... print "Match!"
...
Match!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值