python学习一

#-*- encoding: utf-8 -*-
'''
Created on 2013-*-*

@author: ****
'''

import sys
from locale import str
sys.stdout.writelines("this is test\n")

str = "start to learn python"
print str
str

print "%s is numner %d" % ('python',1)

print >> sys.stderr, "this is invalid data"

logfile = open("mylog","w")
print >> logfile, "invalid data"
logfile.close()

#num = raw_input("enter a numner:")
#print "double numner is %d" % (int(num)*2)

#help(open)

print 5.0/2.0
print 5.0//2.8

print 3*3
print 3**3

print -2*4 + 3**2

str1 = "this is test"
str2 = "good mornin"
print str1+str2
print str2[0]
print str2[len(str2)-1]
print str2[-1]
print str1*2
#列表
alist = [1,2,3,4]
print alist
print alist[1:]
print alist[2:4]
#列表的值可以更改
alist[0]=11
print alist

atuple = ("this" , "is", "test", "data")
print atuple
print atuple[2:4]
#元祖的值不能更改

adict={"host":"10.68"}
adict["id"]=11
print adict

print adict.keys()

for elem in adict.keys():
    print elem, adict[elem]

counter = 0
while counter <= 3:
    print "counter = %d" % (counter)
    counter += 1
 
for num in range(4):
    print num,
print    
    
for c in range(len(str1)):
    print "index =%d" % (c), "values = %c" % (str1[c])  
print      

for i, ch in enumerate(str1):
    print i, "values =%s" % (ch),
print    

squre = [x+5 for x in range(4) if x % 2 !=0]
for x in squre:
    print x
 
try:    
    fp = open("b.txt","r")
    for eachline in fp:
        print eachline,
    fp.close()
except IOError,e:
    print e   
print    
 
def addmetome(x):
    return x+x

print addmetome(4)
print addmetome("test")
print addmetome([1,4,5])      


def foo(debug = True):
    if(debug):
        print "this is debug model"
    else:
        pass
foo()
foo(False)          

class FooClass(object):
    version=1.0
    if __name__ == '__main__':
        print "test"
    def __init__(self,name = "wjc"):
        self.name=name
        print "create class instance for %s" % (name)
    def showname(self):
        print "yourname is %s" % (self.name)    
        print "myname is %s"  % (self.__class__.__name__)
    def showversion(self):
        print "current verison is %d" % (self.version) 

myfoo = FooClass("haha")
myfoo.showname()
myfoo.showversion()           
        
print sys.platform
print sys.version       

print "------------------------" 
print dir()

#服饰语句不会返回一个值(y=(x=2) is error),但是可以使用链式赋值
y=x=2
print x,y
(x,y,z) = (12,23,34)
print x,y,z
#直接交换赋值 不需要中间变量    
(x,y)=(y,x)
print x,y,z
#删除对象的引用后,对访问都是不起作用的
#del x
print type(type(42))

alist1=[]
if alist1==False:
    print "false"
else:
    print "true"
    
str1="abcdefg" 
print str1[::-1]

a=1
b=a
print a,b   
print type(a).__name__
print a is b
print id(a), id(b)
c=1.0
d=1.0
print id(c),id(d)
print id(a)==id(b)
b=3;
print a,b
print a is not b
print id(a)==id(b)
print cmp(a,b)
print repr(a)
print type(0+0j)
print type([]),type(()),type({})

class Foo:
    pass
foo=Foo()
print type(foo).__name__
print type(Foo),type(foo)
print isinstance(foo,Foo)
#help(isinstance)

class obj(object):
    pass
obj1=obj()
print type(obj),type(obj1)

x="this is test"
print id(x)
x="yy"
print id(x)

print 2<<32

print 1//2
print -1//2
print 4**-1
print 8.0/3.0

print cmp(1,2)
print type(1)

print long(42)

print complex(4)
print abs(3+4j)
print divmod(5,2)

print round(3.0)
print round(3.4)
print round(3.5,1)
print round(3.49,1)
print hex(255)

print ord('a')
print chr(97)

class Tc:
    def __nonzero__(self):
        return False
mytc = Tc();
print bool(mytc)
print bool(Tc)

alist= [100,200,300,400]
print alist[-100:100:1]

s="abcde"
print s[0:5]
s=s[0:2]+s[3:]
print s

print "%s" "%s" % ("this","test")
print " ".join(("this", "is","test"))
print "hello""faf"
print "\\n"
f = open('C:\\c++\\mlc.log.201303211054', 'r') 
print f.readline()
f.close()
print isinstance("u",basestring)
print isinstance("u",unicode)

print chr(123)
print "abc".capitalize()
print "abc".center(5)
print "abcabca".count("a",0,10)
print "abcabc".endswith("a")
print "abeabc".find("r",0)
#substring不在字符串中,则raise一个异常
print "abcabc".index("ab",0)
print "abc".isalnum()
print "abc".isalpha()

print "Abc".islower()

print "abc this txt".split(" ")
print "Abc tHis txt".swapcase()
print "abc".zfill(7)

print '''this 
faf \t
\n\t taf'''

s ="this is abc"
# 字符串是不可变的
#s[3] ="w"
s=s+"text"#重新分配的字符串
print s

list1=["abc","678"]
list2=["def","123"]
print list1<list2
print list1+list2

print max(list1)

list1=["abc","tasfasf","Abc","hfa","gq3g"]
for s in reversed(list1):
    print s,
print    
print sorted(list1)


def sumlist(l):
    sum = 0
    for ele in l:
        sum+=int(ele)
        print "sum=" % sum
    return sum

print list1 ,tuple(list1) 

alist =list(tuple(list1))
print list1 is alist

#print dir(list)
list1.append("haha")
print list1

for ele in list1:
    if ele in list1:
        print list1.index(ele)


list1.extend(("app1","app2"))
print list1

mod = []
mod.extend(("app1","app2"))
print mod
print mod.pop()
print mod

person = ["name",["saving",100]]
#队员元祖只是一个浅拷贝
hc=person[:]
import copy
#深拷贝
wc=copy.deepcopy(person)
#浅拷贝
#wc=copy.copy(person)
#wc=list(person)


print hc, wc
hc[0]="john"
wc[0]="linlin"
print hc, wc
hc[1][1]=50
#person[0]  不变,是因为是字符串,不能更改#['john', ['saving', 50]] ['linlin', ['saving', 100]] ['name', ['saving', 50]]
print hc, wc, person

#以下是字典部分 映射
dict1={"one":"neusoft","two":"yisibo"}
print dict1
dict2=dict((("one","neusoft"),("two","yisibo")))
print dict2
dict3=dict((["one","neusoft"],["two","yisibo"]))
print dict3

dict4={}.fromkeys(('x','y'),1) #{'y': 1, 'x': 1}
print dict4
dict5={}.fromkeys(('x','y'))#{'y': None, 'x': None}
print dict5

for key in dict2.keys():
    print "key=%s values=%s" % (key,dict2[key])
for key in dict2:
       print "key=%s values=%s" % (key,dict2[key])  
print dict2.has_key("one")      #True
#in/not in 只能用于key
print "one" in dict2 #ture
print dict2.has_key("fuck")  #False

del dict2["one"]
dict2.pop("two")
dict2.clear()

dict6=dict(x=4,y=5)
print dict6
dict7=dict(dict6)
dict8=dict.copy(dict6)
print dict7,dict8

print len(dict7)
#hash()判断是否可以作为字典的键
#print hash([]) #TypeError: unhashable type: 'list'

#dict0[[]] = "foo" #error[] 不能作键

print dict7.keys(),"-------",dict7.values(),"------",dict7.items()

sorted(dict7)#返回一个有序的
print dict7
#get得到value时候,当key不存在,可以设置默认值
print dict7.get("x") #4
print dict7.get("xxx") #None
print dict7.get("xxx","no value") #no value
#fromkeys(),不设置value返回None,或者设置key的默认值
dict10={}.fromkeys("xyz")
print dict10 #{'y': None, 'x': None, 'z': None}
dict11={}.fromkeys("xyz",10)
print dict11 #{'y': 10, 'x': 10, 'z': 10}

str1="this is test"
print str1.strip() #this is test
print str1.strip()[0] #t
print str1.strip()[1] #h
print str1.strip()[2] #i

tuple1=("this","is","test","tuple")
try:
    i=iter(tuple1)
    print i.next()
    print i.next()
    print i.next()
    print i.next()
    #print i.next() #测试到尾部的时候将引发异常
except StopIteration:
    pass
#文件类型的迭代器自动调用readLine()方法
 #for conttent in fp = for countent in fp.readLine()
#迭代用于可变对象会很危险

#文件操作
import os
#得到文件大小
print os.stat("b.txt").st_size
fp=open("b.txt","r")
fp.seek(0)
#统计单词个数  
print sum(len(word) for line in fp for word in line.split())








#output
this is test
start to learn python
python is numner 1
this is invalid data
2.5
1.0
9
27
1
this is testgood mornin
g
n
n
this is testthis is test
[1, 2, 3, 4]
[2, 3, 4]
[3, 4]
[11, 2, 3, 4]
('this', 'is', 'test', 'data')
('test', 'data')
{'host': '10.68', 'id': 11}
['host', 'id']
host 10.68
id 11
counter = 0
counter = 1
counter = 2
counter = 3
0 1 2 3
index =0 values = t
index =1 values = h
index =2 values = i
index =3 values = s
index =4 values =  
index =5 values = i
index =6 values = s
index =7 values =  
index =8 values = t
index =9 values = e
index =10 values = s
index =11 values = t


0 values =t 1 values =h 2 values =i 3 values =s 4 values =  5 values =i 6 values =s 7 values =  8 values =t 9 values =e 10 values =s 11 values =t
6
8
thisistest
I love Python!
Hello, world
Good Bye!


8
testtest
[1, 4, 5, 1, 4, 5]
this is debug model
test
create class instance for haha
yourname is haha
myname is FooClass
current verison is 1
win32
2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
------------------------
['FooClass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'addmetome', 'adict', 'alist', 'atuple', 'c', 'ch', 'counter', 'eachline', 'elem', 'foo', 'fp', 'i', 'logfile', 'myfoo', 'num', 'squre', 'str', 'str1', 'str2', 'sys', 'x']
2 2
12 23 34
23 12 34
<type 'type'>
true
gfedcba
1 1
int
True
24752616 24752616
24786160 24786160
True
1 3
True
False
-1
1
<type 'complex'>
<type 'list'> <type 'tuple'> <type 'dict'>
instance
<type 'classobj'> <type 'instance'>
True
<type 'type'> <class '__main__.obj'>
26337432
27023888
8589934592
0
-1
0.25
2.66666666667
-1
<type 'int'>
42
(4+0j)
5.0
(2, 1)
3.0
3.0
3.5
3.5
0xff
97
a
False
True
[100, 200, 300, 400]
abcde
abde
thistest
this is test
hellofaf
\n
2013-03-21 10:54:22.304 [TID#1067]  [Info] Motorola Location Controller has been started


True
False
{
Abc
 abc 
3
False
-1
0
True
True
False
['abc', 'this', 'txt']
aBC ThIS TXT
0000abc
this 
faf 	


	 taf
this is abctext
True
['abc', '678', 'def', '123']
abc
gq3g hfa Abc tasfasf abc
['Abc', 'abc', 'gq3g', 'hfa', 'tasfasf']
['abc', 'tasfasf', 'Abc', 'hfa', 'gq3g'] ('abc', 'tasfasf', 'Abc', 'hfa', 'gq3g')
False
['abc', 'tasfasf', 'Abc', 'hfa', 'gq3g', 'haha']
0
1
2
3
4
5
['abc', 'tasfasf', 'Abc', 'hfa', 'gq3g', 'haha', 'app1', 'app2']
['app1', 'app2']
app2
['app1']
['name', ['saving', 100]] ['name', ['saving', 100]]
['john', ['saving', 100]] ['linlin', ['saving', 100]]
['john', ['saving', 50]] ['linlin', ['saving', 100]] ['name', ['saving', 50]]
{'two': 'yisibo', 'one': 'neusoft'}
{'two': 'yisibo', 'one': 'neusoft'}
{'two': 'yisibo', 'one': 'neusoft'}
{'y': 1, 'x': 1}
{'y': None, 'x': None}
key=two values=yisibo
key=one values=neusoft
key=two values=yisibo
key=one values=neusoft
True
True
False
{'y': 5, 'x': 4}
{'y': 5, 'x': 4} {'y': 5, 'x': 4}
2
['y', 'x'] ------- [5, 4] ------ [('y', 5), ('x', 4)]
{'y': 5, 'x': 4}
4
None
no value
{'y': None, 'x': None, 'z': None}
{'y': 10, 'x': 10, 'z': 10}
this is test
t
h
i
this
is
test
tuple
53
41



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值