python学习笔记一:基本数据类型

1、python的一切都是对象,对象是包含属性和方法的一个整体。

2、数据类型的组成:身份 (内存地址,通过id方法可看它的唯一标识符);类型(通过type方法查看);值(数据项)

3、常用基本数据类型

  • int  整型
  • bool  布尔 
  • strintg   字符串
  • list   列表
  • tuple 元组
  • dict  字典

4、数据类型的可变和不可变

  • 不可变类型:int, string,tuple
  • 可变类型:list,dict

5、 转义字符

#转义字符
print('abcd\nef')#\为转义字符
print(r'abcd\nef')#字符串前面加r表示不转义

运行结果:
abcd
ef
abcd\nef

6、切片

a = "abcde"
b = a[-1] #访问最后一个元素
c = a[0:4]#访问序列在0到4之间的元素不包括4
print(b)
print(c)

运行结果:
e
abcd

7、字符串替换

a = "abcd"
print(a[0])
b = a.replace('d','def')
print(b)
print(a.find('d'))#字符串查询

运行结果:
a
abcdef
3

8、字符串拼接


#【1】直接相加
a = 'my name is xiaobin'
b = 'tong'
c = a + b
print(c)

运行结果:
my name is xiaobintong

#【2】占位符
print('my name is %s xiaobin' % 'tong')#%s为字符串占位符,%d为数字占位符
print('my name is %s xiaobin,i\'m %s years old' % ('tong',24))

print('my name is {1}, i\'m {0} years old'.format('24','tongxiaobin'))#用format方法

运行结果:
my name is tong xiaobin
my name is tong xiaobin,i'm 24 years old
my name is tongxiaobin, i'm 24 years old

#【3】join
a = '123'
b = '456'
c = '789'
d = ''.join([a,b,c])
e = ';'.join([a,b,c])
print(d)
print(e)
运行结果:
123456789
123;456;789

9、文件操作:‘r’-read; 'w'-write;‘a’-append(在最后添加)

#写操作
d = open('1.txt','w')
d.write('hello world\nmy name is tongxiaobin')
d.close()

#读操作
e = open('1.txt','r')
print(e.readline())#按行读取
print(e.readline())

运行结果:
hello world
my name is tongxiaobin

#末尾添加操作
a = open('1.txt','a')
a.write('\ncome from anhui')
a.close()

打开文件结果为:
hello world
my name is tongxiaobinfdsd
come from anhui

10、linecache模块

import linecache
linecache.getline('1.txt',2)

运行结果:
'my name is tongxiaobin\n'

linecache.getlines('1.txt')

运行结果:
['hello world\n', 'my name is tongxiaobin\n', 'come from anhui\n']

猜你喜欢

转载自blog.csdn.net/qq_24946843/article/details/83116597