Python入门之基本数据类型

来源:互联网 发布:卫计委 医疗大数据 编辑:程序博客网 时间:2024/04/29 06:35

数据类型的组成

由3部分组成:


  • id:通过id方法查看它的唯一标识,内存地址
  • type:数据类型

python 里面一切都是指针

基本数据类型


  • int
  • boolean
  • 字符串,也称之为“序列”
  • 列表
  • 元组 tuple
  • 字典

类型也分为可变类型和不可变类型;其中可变类型:int ,string,tuple(a=(1,2,3));可变类型如list,tuple,dict
注意:python虽然是动态语言,但是如果变量的类型确定了之后,就不能更改。

整型与boolean

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

字符串的认识

python 默认的编码方式 ascii码

  1. len() 方法的使用

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

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

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

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

    print "abc\n" //返回结果是 abc 加换行的文本print r"\n" //r表示不要转移  ,故结果是 \nprint u"abc" //u 表示是unicode编码

    3.子串

    a = "abcdef"a[0] //返回值是 aa[len(a)-1] //返回值是fa[-1] //返回值是 fa[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 %sa = "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

原创粉丝点击