Python 学习基础知识之简单demo-1

这篇博客记录了Python学习的基础知识,包括字符串练习,如何找出字符串中字符的出现次数,字符串拼接,循环与函数的运用,以及文件的读取方法,如read、readline和readlines。强调了read操作后文件指针的位置问题,以及不同文件打开模式的含义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.2019-2-14,关于字符串的练习
从一串字符中找出y 个数和下标和count函数功能类似

#-*- coding: UTF-8 -*-
# while demo
whstr="jhgjgjhgjfyuifghgfyT6ytyht736878"
n = 0
l=len(whstr)
list1 = []
while l> 0:
    if whstr[n]=='y':
        list1.append(n)
    n += 1
 l=l-1
print "字符串中y字母个数是: "+str(len(list1))
print "y字母的下标是:"+str(list1)

遇见的问题:1.while弄成了死循环,2.字符串和int类型不可以一起输出的(方法:把int 强制转换成str()输出)

2.2019-2-15,字符串拼接练习
字符串的连接方式

coding:utf-8

#字符串拼接方式demo

str1="christina"
str2=" say hello"
str3=''.join([str1,str2])
str4=str1+" "+str2
print "join拼接方式输出 : "+str3
print "'+'拼接方式输出 : "+str4
print "','连接方式输出 : "+str1,str2
print "直接连接方式输出 : "+str1+str2

特别需要注意:join 函数是对列表的使用

3.2019-2-16,循环练习和函数
打印乘法表

coding:utf-8

def mul_function(n):
    while n>0:
        j=n
        for j in range(1,n+1):
            print str(n)+"*"+str(j)+"="+ str(n*(j)),
            j-=1

 print "\n"
 n -= 1
if __name__== '__main__':
    mul_function(9)

1,打印不换行

2.range(a,b) 的区间是[a,b-1]

4.2019-2-19,文件操作,关于文件的读取

coding: utf-8

#文件读取的方法

fo = open("D:\chrisdoc\chis.txt", "w+")
i=0
j=5
for i in range(i,j):
    fo.write("christina write by python:\n")
    i+=1
fo.close()
f1 = open("D:\chrisdoc\chis.txt", "r")
str = []
line = f1.readline()
while line:
    print line
    line=f1.readline()
fo.close()

1.read()读取所有字节,readline()读取单行,readlines()读取所以行,读取结果以列表方式储存且包含了后面的换行符

2.readline 更适合大文件,

3.说说自己遇见的一个问题,在写demo的时候想把readline 和read 一起写,结果read之后,read 出来一直为空,后来通过查阅资料才发现,read一次之后,文件就处于末尾,所以再read就为空。

4.w–只写,如果文件存在会清空当前文件的内容再写,如果不存在先创建

a --可以读写,在文件末尾继续编辑

r–只读

w+ --读写(清空)

r±- 读写

a±-读写

5.2019-2-20,s时间操作

coding: utf-8

import time
now=time.localtime(time.time())
fnow=time.localtime()
asnow=time.asctime()
print "当前时间时间蹉:",now
print "当前时间年月日:",fnow
print "当前时间:",asnow
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值