第三节课: Python 基本数据类型讲解(3/3)


一、类型
1. 不可变类型 string, int, tuple
2. 可变类型 list, dict

>>> a = "test"
>>> a[0]
't'
>>> a[0]=e
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'e' is not defined
>>> a = ["t","e","s","t"]
>>> a[0]
't'
>>> a[0]="e"
>>> a
['e', 'e', 's', 't']

二、再究字符串
序列到底是什么? 老鹰 和 小鸡
1. 三个符号的区别 ‘’,“”, """ """
print "this is 1'"
print 'this is 2"'
print """
'this is 1"'
"this is 2'"
"""
2. 偏移量从0开始
3. 如何修改字符串之 replace find

从下面的语句中,我们要知道a.replace之后 a是不会变化的, 如果需要变化后的值一定要赋值。

>>> a = "this is world"
>>> a.replace("this","that")
'that is world'
>>> a
'this is world'
>>> a = a.replace("this","that")
>>> a
'that is world'
>>> a.find("world")
8
>>> a.find("www")
-1
>>> a[8]
'w'
>>> a[8:]
'world'


如果匹配到多个值,应该怎么办呢?
>>> help(a.find)
Help on built-in function find:

find(...)
S.find(sub [,start [,end]]) -> int

Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.

>>> a = "world, world, world"
>>> a.find("world")
0
>>> a.find("world",11)
14

三、格式化细究
1. %格式化方法 (占位符)

>>> a = "world, world, world"
>>> a.find("world")
0
>>> a.find("world",11)
14
>>> a = "this is a %s %s" % (4, 10)
>>> print a
this is a 4 10


2. format格式化方法

调用方式 b = "this is {} {}".format("apple","my")
位置方式 b = "this is {1} {0}".format("apple","my")
标识符方式 b = "this is {whose} {fruit}".format(fruit = "apple", whose = "my")


3. 为什么要用format
4. 还有一个方法, 字典来了

a = "this is %(whose)s %(fruit)s" % {'whose':'apple', 'fruit':'my'}


四、再议打开文件

写好文件后要关闭文件
a = open("tmp1.txt","w")
a.write("this is a apple")
a.close()

读文件之间要 打开并读文件,将文件赋给变量
a = open("tmp1.txt","r")
a.read(20)
a.seek(0)
a.read(20)

标准库介绍 linecache

>>> a.write("haha haha sfasdda sdfsa")
>>> a.close()
>>> import linecache
>>> print linecache.getline("tmp2.txt",1)
haha

>>> print linecache.getline("tmp2.txt",2)
haha

>>> print linecache.getline("tmp2.txt",3)
sfasdda

>>> print linecache.getline("tmp2.txt",4)
sdfsa

>>> lines = linecache.getlines("tmp2.txt")
>>> print lines
['haha ', 'haha ', 'sfasdda ', 'sdfsa ']
>>> help(linecache)
NAME
linecache - Cache lines from files.

FILE
d:python27liblinecache.py

DESCRIPTION
This is intended to read lines from modules imported -- hence if a filename
is not found, it will look down the module search path for a file by
that name.

FUNCTIONS
checkcache(filename=None)
Discard cache entries that are out of date.
(This is not checked upon each call!)

clearcache()
Clear the cache entirely.

getline(filename, lineno, module_globals=None)

DATA
__all__ = ['getline', 'clearcache', 'checkcache']

可以查看源代码,

看源代码, 其实很是挺简单的. 不要畏难, 没有什么东西搞不懂的, 一旦畏难就会产生距离感。
多练习, 不要光学理论. 硬着头皮看东西, 有问题多问. (老师说的这句话我还是非常认同的)

原文地址:https://www.cnblogs.com/huiming/p/5510547.html