您的位置:首页 > 编程语言 > Python开发

Python入门之基本数据类型

2017-07-23 01:14 417 查看

数据类型的组成

由3部分组成:

id:通过id方法查看它的唯一标识,内存地址

type:数据类型



python 里面一切都是指针

基本数据类型

int

boolean

字符串,也称之为“序列”

列表

元组 tuple

字典

类型也分为可变类型和不可变类型;其中可变类型:int ,string,tuple(a=(1,2,3));可变类型如list,tuple,dict

注意:python虽然是动态语言,但是如果变量的类型确定了之后,就不能更改。

整型与boolean

print 1==1 //true
print 1=="1" //虽然值相同,但是类型不同
bool(1==1) //该表达式的“结果”是true


字符串的认识

python 默认的编码方式 ascii码

len() 方法的使用

a="1234"
len(a)  //返回结果是 4
a=“哈”
len(a) //返回结果是3
a= u"哈”
len(a) //返回结果是1
a="哈哈哈"
g=a.decode("utf-8")
len(g) //返回结果是3


创建一个.py文件,文件的内容如下:

#coding = utf-8
a = “哈哈”.decode("uft-8")
print len(a)


2.转义字符

将要转意的字符前面加上 “\”

print "abc\n" //返回结果是 abc 加换行的文本

print r"\n" //r表示不要转移  ,故结果是 \n
print u"abc" //u 表示是unicode编码


3.子串

a = "abcdef"
a[0] //返回值是 a
a[len(a)-1] //返回值是f
a[-1] //返回值是 f
a[0:] //返回值是 "abcdef"
a[1:2] //返回值 b


4.替换方法 replace(old,new)

a = "abc"
g = a.replace('a','cccc')
print g   //返回值 ccccbc


5.拼接字符串

a= "abc"
b="def"
print a+b  //显示值 "abcdef"

//优化的解决办法,通过"占位符"
print "my name is %s" %"zhang" //返回值结果是
my name is zhang
//多个占位符
print "%d world, one %s" %(1,"dream")

//join方法实现拼接
a = "zhang"
b = "wang"
c = "li"
print "".join([a,b,c])  //输出结果是 zhangwangli
print ",".join([c,b,a]) //输出结果是 li,wang,zhang


6 文件打开

//写入文件
a = open("a.txt",'w')
a.write("hi\nsecond hi.")
a.close() //一定要关闭流

//读取文件
r = open("a.txt",'r')
print r.readLine(); //读取一行
print r.read(1000); //读取1000字节


7 符号区分

’ ‘

“”

“”” “”” : 连续三个”“” 表示是一个多行文本

8 字符串的内置方法

replace

a = "this is the world"
print a.repleace("this","that")
// that is the world


find

定位子字符串的位置

9.占位符的描述

%d %s
a = "this is %s %s" %("my","apple")
b = "this is {1} {0}".format("my","apple")
c = "this is {whose} {fruit}".format(fruit="apple",whose="my")
//通过字典
d = "this is %(whose)s %(fruit)s" %{'whose':'my','fruit':'apple'}


10 文件读写 import linecache
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 入门