python基础

本文详细介绍了Python的基本概念,包括变量类型、类型转换、布尔类型、字符串操作等,还讲解了文件的读写方法及linecache模块的使用。

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

python中一切都为对象,python中数据类型:

  • 不可变变量: int, string, tuple(元祖)
  • 可变变量:list(列表), dict(字典)
[注意]
python中数据都是指针,变量用于指向内存中内容的存放地址,当修改某一不可变变量时,实际上是修改了它的指向地址,而不是将原来的指向只地址上的内容改变,id(a)适用于求a这个变量的唯一标识:
>>> a = 10
>>> id(a)
140419272824672
>>> a = 21
>>> id(a)
140419272824408


上面可以看到,对变量a重现赋值之后,a的id标示发生了改变,说明变量a的指向发生了改变。

对于可变变量list和dict:
>>> a = [1,2,3,4]
>>> id(a)
4369270832
>>> a.append(0)
>>> a
[1, 2, 3, 4, 0]
>>> id(a)
4369270832


上图中a为list(可使用type(a)查看变量的类型),可以发现在append前后,id(a)并没有发生变化。

变量的类型转换:
不同类型的变量之间的操作需要首先进行变量类型转换:
>>> a = "111"
>>> b = 1
>>> print int(a) + b
112
>>> print a + str(b)
1111
>>> print a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects


对上面的变量a和b,在a,b进行操作之前,若不进行类型的转换,会报错。

python中的bool类型为:True和False。

>>> 1 == 1
True
>>> 1 == "1"
False
>>> a = True
>>> type(a)
<type 'bool'>

python中的三引号"""的作用,是可以包含多行内容:

>>> a = """
... 这是python
... 多行输入
... 可以输入很多行
... hust
... """
>>> a
'\n\xe8\xbf\x99\xe6\x98\xafpython\n\xe5\xa4\x9a\xe8\xa1\x8c\xe8\xbe\x93\xe5\x85\xa5\n
\xe5\x8f\xaf\xe4\xbb\xa5\xe8\xbe\x93\xe5\x85\xa5\xe5\xbe\x88\xe5\xa4\x9a\xe8\xa1\x8c\nhust\n'

python中字符串的replace,find

replace是为了替换字符串中的一部分,但需要注意的是,replace函数不会改变字符串的指向,需要将字符串replace之后赋值给原来的字符串才能够达到替换的效果:

>>> a = "Hello World, I am Hust"
>>> a
'Hello World, I am Hust'
>>> a.replace("Hello", "Hi")
'Hi World, I am Hust'
>>> a
'Hello World, I am Hust'
>>> a = a.replace("Hello", "Hi")
>>> a
'Hi World, I am Hust'

从上面的代码可以看出,a.replace("Hello", "Hi")并没有改变a字符串的内容,只有a = a.replace("Hello", "Hi"),就可以替换a的内容,但替换之后,id(a)也发生了改变,说明a的指向也发生改变。

find是为了查询字符串中有没有子字符串:

>>> a
'Hi World, I am Hust'
>>> a.find("hust")
-1
>>> a.find("Hust")
15
>>> a[15]
'H'

find若找不到子字符串,则会返回-1,若找到,则返回子字符串在父字符串中第一个下标。

当查找字符串中多个相同的子字符串时,find()只会返回第一个字符串的下标,可以使用help(a.find)来查看find函数使用方法:

>>> 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.
(END)

从上面可以看到,find函数中start和end是可选参数,start和end是可选参数,用于查找字符串中指定范围内的子字符串的下标:

>>> a = "Hello World Hello Hello Hello"
>>> a
'Hello World Hello Hello Hello'
>>> a.find("Hello")
0
>>> a.find("Hello", 4)
12


字符串的格式化:
(1)%格式化方式, 字符串使用%s , 数字使用%d 进行格式化:

>>> a = "this is a %s" % "apple"
>>> a
'this is a apple'

如果有多个字符串需要格式化:

>>> a = "I have %d %s" % (10, "apples")
>>> a
'I have 10 apples'


(2)format格式化方式

>>> a = "I have {} {}".format(12, "apples")
>>> a
'I have 12 apples'

format也可以不按照顺序来格式化字符串:

>>> a = "I have {1} {0}".format("apples",12)
>>> a
'I have 12 apples'

format格式化字符串,还可以有更为直观的方式:

>>> a = "I hava {num} {fruit}".format(fruit="apples", num=12)
>>> a
'I hava 12 apples'

同样的使用%的方式也可以完成直观的格式化的方式:

>>> a = "I have %(num)d %(fruit)s" % {'fruit':'apples', 'num':12}
>>> a
'I have 12 apples'

需要注意的是,这种方式在%后面,使用一个dict字典指定。


使用python读写文件:

>>> a = open("tmp.txt", "w")
>>> a.write("this is a python test file")
>>> a.close()
>>> 
>>> a = open("tmp.txt", "r")
>>> a.read(500)
'this is a python test file'
>>> a.read(30)
''
>>> a.seek(0)
>>> a.read(20)
'this is a python tes'

open("tmp.txt", "w")是以write的模式打开指定路径的文件,write()函数中只能够写入str,需要注意的是,上面的a.read(30)之所以读不出内容,是因为上面的a.read(500)已经将a的游标移动到了500的地方,在a.read(30)之前,需要通过a.seek(0),将游标移动到起始的位置。


使用linecache读取文件:
使用help(linecache)可以查看linecache的用法,使用linecache之前,需要import linecache

>>> import linecache
>>> help(linecache)


MODULE DOCS
    http://docs.python.org/library/linecache

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']

(END)


首先在tmp.txt文件中写入多行内容:

a = open("tmp.txt", "w")
>>> a.write("this is line1\nand line2\nand line3\nline4")
>>> a.close()

使用linecache.getline(filename, linenum)读取文件filename中的第linenum行的内容:

>>> import linecache
>>> 
>>> print linecache.getline("tmp.txt", 1)
this is line1

>>> print linecache.getline("tmp.txt", 2)
and line2

>>> print linecache.getline("tmp.txt", 3)
and line3

还可以使用linecache.getlines(filename)读取filename文件中所有行的内容(以list形式输出):

>>> linecache.getlines("tmp.txt")
['this is line1\n', 'and line2\n', 'and line3\n', 'line4\n']


linecache是使用了一个全局的dict字典,内部使用open函数将文件中的内容全部读取完毕,并放置到dict中,供查询使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值