Python基础

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

也是自己之前学习的笔记。

读文件

file_obj2=open('hello.txt','w')

conta='my name is Bb'file_obj2.write(conta)

v=file_obj2.readlines()PRintv

输出不唯一数1 (这是一个国外Python练习网站上的题目 我其他博文有介绍 )

defcheckio(data):fromcollectionsimportCounter

nonunique= Counter(data) -Counter(set(data))return[xforxindataifxinnonunique]printcheckio([1,31,5,13,13,1,1])printcounter(set([1,31,5,13,13,1,1]))

输出不唯一数2

#Your optional code here#You can import some modules or create additional functionsdefcheckio(data):return[xforxindataifdata.count(x) > 1]#Some hints#You can use list.count(element) method for counting.#Create new list with non-unique elements#or remove elements from original list (but it's bad practice for many real cases)#Loop over original list#These "asserts" using only for self-checking and not necessary for auto-testingif__name__=="__main__":assertisinstance(checkio([1]), list),"The result must be a list"assertcheckio([1, 2, 3, 1, 3]) == [1, 3, 1, 3],"1st example"assertcheckio([1, 2, 3, 4, 5]) == [],"2nd example"assertcheckio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5],"3rd example"assertcheckio([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9],"4th example"

#python while 循环语句

i=1;

s=0;whilei<=100:prints,i

s=s+i

i=i+1print'exit'

#第八课 python自定义函数预定义 1.预定值放在前面 2. 后面赋值可以把先前预定的值覆盖#

deftest_e(n1,n2=15):printn1printn2returnn1+n2

test= test_e(2)printtest

#python函数实参赋值顺序#

deftest_e(val1,val2,val3):printval1printval2printval3returnval1+val2+val3

test_e(5,23,55)

#python赋值 进行一一对应的赋值 以防出现错误#

#python if语句#

#注意使用 raw_input()的时候 把字符强制转化成 整形#

count =int(raw_input('input your number:'))printcountifcount>=80:print'a'elifcount>=70:print'b'else:print'nono'

#字符区域代码#

sex=raw_input('put your sex')ifsex=='Male':print'right'else:print'no'

#python if分支语句表达式构造 非0 即为真#

#关系表达式 > < = 逻辑表达式 and or not

#网络刷博客浏览量#

import os

importwebbrowser as webimporttime

i=0whilei<=10:

web.open('http://blog.sina.com.cn/s/blog_9a0d1f710101vm5k.html?tj=1')

time.sleep(0.8)

os.system('taskkill /F /IMChrome.exe')print'%d times already run'%i

i=i+1

#循环体for基础#

list1=[2,65,'g',5656]#list 数据类型i=0;forlistsinlist1:printformat(i,'2d'),lists

i=i+1

#string 数据类型

j=0;

string='hello world'list2=list(string)#forstrinlist2:#string 直接用数据也可以printformat(j,'2d'),str;

j=j+1;

k=0;forkinrange(1,101,2):#range 函数 范围在 start 到 end-1 最后一位为每个数字间隔数printk;

s1='hello world'

#for循环 循环体遍历文件和元组#

tup = (1,2,3,4,5)#tup 元组fortupsintup:printtups#file.readlines 获取文件列表 file.readline 获取文件字符串第一行#记住 open 的用法str =open('python16.py','r').readline()printlen(str)forcinopen('python16.py','r').readlines():printc;

open('temp.txt','a++').write(r)#在原目录下面增加一个txt文件 在文件里面写入打开的文件内容

#python 字符串基础

#转移字符串printr'hello\nworld'#r关闭转义字符串的作用printu'unicode'#unicode 字符串#格式化字符串print'your age is %d'%(28)

#open('c:\\temp\\temp.txt','a+') 用一个‘、’可能被认为是转义字符

#字符串基本操作

s1='www.hxend's2='.com'prints1,s2#这样输出的话 中间会存在一个空格prints1+s2#用‘+’连接两个字符串#字符串的重复 *s='abcdefg'prints*5

#访问字符串的某个元素 index索引ch = s[3]printch#python 切片 slice s[i:j]sub =s[3:5]#从 start 到 end-1printsubprints[:5]prints[3:]prints[-4:-1]#如果发生错误 就会出现 空格表示#s[i:j:k]prints[-1:-4:-1]#倒序输出 依次减一s2='www.hxend.com'prints2[9:4:-1]prints2[-1:0:-1]prints2[-1::-1]#用for 循环遍历整个字符串s5='www.hxend.com'forchins5:printch;

#字符串的高级函数

#isalnum 判断是否为 数字或者为字母 s.isalnum()s='wwwhxend55com'prints.isalnum()#s.isalpha 判断是否为字母s='abcdef'prints.isalpha()#s.isdigit() 判断是否为数字s='626611'prints.isdigit()#s.islower s.isupper 判断大小写s='FDFD'prints.islower()prints.isupper()#s.isspace 判断是否为 空格s=''prints.isspace()#s.upper() s.lower() 大小写互换s='sdgsdgsJLKF'prints.upper()#字符串查找 s.startswith() s.endswith() 返回 bool值s='www.hxend.com's1='www'prints.startswith(s1)prints.endswith(s1)#find 函数 s.replace('','') 函数代替 找到即可替换s='www.hxend.com'ifs.find('hxend'):

s5=s.replace('hxend','baidu')#不改变原来的值prints5

#字符串分割函数

s='abcdef 1515 dhgghl sdjgsjdg hgkjdhgjk g gskdj gjkg kjsd'prints

list1=s.split()printlist1printlen(list1)#s.strip() 去掉字符串开头 和结尾的 空格s1=s.strip()prints1#find 函数返回 出现这个字符的位置 找不到 返回 -1a= s1.find('c')printa

s1=list(s1)prints1#s.find('',k) find 从k开始#s.find('') find 从头开始importmath

s1=s.strip()

a=s1.find('')prints1[:a]

list11=s1.split()

lens=len(list11)printformat(lens,'2d')#format 的用法i=0forninrange(0,lens-1):#动态变化次数whiles1[a] =='':

a=a+1b=s1.find('',a)ifb!=-1:#考虑到后面结尾部分 不存在空格了prints1[a:b]else:prints1[a:]

a=b'''count = 5 #这里也是动态变化次数的方法之一

for i in list1:

if count == 0:

pass

else

# do sth here...

count = count - 1 #'''

#字符串分割函数的实现

s='sdgsdg..sdg.f.gs.dh.sd..fsd.g.sd's1=s.split('.')#分割出字符串 去除'.' 然后录入到列表中去prints1#s.find('',k) find 从k开始#s.find('') find 从头开始#s.find('',k) find 从k开始#s.find('') find 从头开始importmathdefmy_split(sep):

s1=s.strip()

a=s1.find(sep)prints1[:a]

list11=s1.split(sep)

lens=len(list11)printformat(lens,'2d')#format 的用法i=0forninrange(0,lens-1):#动态变化次数whiles1[a] ==sep:

a=a+1b=s1.find(sep,a)ifb!=-1:#考虑到后面结尾部分 不存在空格了prints1[a:b]else:prints1[a:]

a=b

my_split('.')

#append()的使用

list2=[2,32,32,23,232,3,2]

list2.append(1)#append() 增加在尾部printlist2

#字典

adict={'mother':45,'father':55}printadict

adict['grandfather']=87#增加在首部printadictprintadict.keys()#名字printadict['father']#提取内容#print 默认为每个输出 输出一个换行 后面加上一个 , 可以改变这个状态a='sdgsdgsdsdh'fori ,chinenumerate(a):#enumrate() 函数printch,i

'''2.13 列表解析

这是个术语, 表示你可以在一行中使用一个for循环将所有值放到一个列表 当中: '''

sqdEvens = [x ** 2forxinrange(8)ifnotx % 2]printsqdEvens`'''handle = open(file_name,access_mode = 'r')

file_name 变量包含我们希望打开的文件的字符串名字, access_mode 中 'r' 表示读取,

'w' 表示写入, 'a' 表示添加。'''file1=open('second.py','r')#文件操作printfile1.readline()#print file1.read()a=file1.readlines()#readlines() 自动将文件内容分析成一个行的列表,#该列表可以由 Python 的 for ... in ... 结构进行处理printa[1]

关于作者:[作者]:——石头——热爱互联网事业,关注互联网技术发展,文章欢迎转载,请保留原文地址,谢谢。

[出处]:http://www.cnblogs.com/webers/

[本文基于]:署名-非商业性使用 3.0许可协议发布,欢迎转载,演绎,但是必须保留本文的署名——石头——(包含链接),且不得用于商业目的。如您有任何疑问或者授权方面的协商,请与我联系

。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航