zoukankan      html  css  js  c++  java
  • 4数据类型(第一篇)

    数据类型(第一篇)

    程序交互

    基本数据类型

    格式化输出

    基本运算符

    流程控制

    1:程序交互

        读取用户的输入:python3支持input输入

        >>>name = input("what's your name")

    what's your name lzj

    >>> print("hello " , name)

    hello lzj

    input("what's your name")

    input()是一个内置函数 "what's your name" 是提示符

    >>> help(input) # 查看这个方法的文档

    Help on built-in function input in module builtins:

    input(prompt=None, /)

    Read a string from standard input. The trailing newline is stripped.

    The prompt string,if given, is printed to standard output without a trailing newline before reading input.If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. On *nix systems, readline is used if available.

    >>> print (type(name))

    <class 'str'>

    而且input()返回值为str类型。

        注释:对代码进行解释说明

        有单行注释:# 还有多行注释:三引号

        注释的原则:不需要对代码全部添加注释,只需要在自己认为重要的地方添加注释;注释可以是中文,英文,但是不能为拼音。

    2:基本数据类型

        数字,字符串,布尔,列表,元组字典集合

        数字:int long(python3中就没有了) float , complex(复数)

        int :

    整数,在python2int有范围的限制,但是在python3中就没有了

    Python中的整数属于int类型,默认用十进制表示,此外也支持二进制,八进制,十六进制表示方式。

    进制转换:

    10进制转换为其他进制:

    10—2

    bin(124)

    '0b1111100'

    bin(225)

    '0b11100001'

        10进制转换为8进制:

    >>> oct(124)

    '0o174'

    >>> oct(225)

    '0o341'

    10进制转化为16进制:

    >>> hex(124)

    '0x7c'

    >>> hex(225)

    '0xe1'

    取余运算:

    >>> 10%3

    1

    >>> 16%4

    0

    >>> 16%7

    2

    算术运算:+ - * / divmod **

    >>> 2+3

    5

    >>> 2-3

    -1

    >>> 2*3

    6

    >>> 3/2

    1.5

    >>> 3//2

    1

    >>> divmod(3,2)

    (1, 1)

    >>> 2**3

    8

    float : 浮点数

    浮点数是属于有理数中某特定子集的数的数字表示,在计算机中用以近似表示任意某个实数。具体的说,这个实数由一个整数或定点数(即尾数)乘以某个基数(计算机中通常是2)的整数次幂得到,这种表示方法类似于基数为10的科学计数法。

    为什么叫做浮点数类型:

    浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,

    一个浮点数的小数点位置是可变的,比如,

    1.23*10912.3*108是相等的。

    浮点数可以用数学写法,如1.233.14-9.01,等等。但是对于很大或很小的浮点数,就必须用科学计数法表示,把10e替代:

    1.23*109就是1.23e9,或者12.3e80.000012可以写成1.2e-5,等等。

    整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的而浮点数运算则可能会有四舍五入的误差

        关于小数不精准的问题:

        Python默认的是17位精度,也就是小数点后16位,尽管有16位,但是这个精确度却是越往后越不准的。

    首先,这个问题不是只存在在python中,其他语言也有同样的问题

    其次,小数不精准是因为在转换成二进制的过程中会出现无限循环的情况,在约省的时候就会出现偏差

        如何在计算的时候设置小数的精度?

    >>> a = 10/3

    >>> a

    3.3333333333333335

    >>> from decimal import *

    >>> getcontext() # 查看当前的精度:prec=28 ,当前的精度为28

    Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])

    >>> getcontext().prec=100

    >>> getcontext()

    Context(prec=100, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])

    >>> a = Decimal(10)/Decimal(3)

    >>> a

    Decimal('3.333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333')

    还有一种:是通过格式化的方式,设置精度

    >>> b = ("%.100f" %(10/3))

    >>> b

    '3.3333333333333334813630699500208720564842224121093750000000000000000000000000000000000000000000000000'

    complex : 复数 ; 复数complex是由实数和虚数组成的

    复数是指能写成如下形式的数a+bi,这里a和b是实数,i是虚数单位(即-1开根)。在复数a+bi中,a称为复数的实部,b称为复数的虚部(虚数是指平方为负数的数),i称为虚数单位

    当虚部等于零时,这个复数就是实数;当虚部不等于零时,这个复数称为虚数。

        字符串:字符串是一个有序的字符的集合,用于存储和表示基本的文本信息,' ''' ''''' '''中间包含的内容称之为字符串

        创建:

         s = "hello girl"

        字符串的特性和常用操作:

        1:按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序

        2:补充:

        a、字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符均取消特殊意义,在引号前面加r,

    >>> name = r'| hf'

    >>> name

    '|\thf'

        bunicode字符串与r连用必须在r前面,如:这个好像不能用了。怎么说呢?在python3str就是unicode , bytes就是bytes; strbytes完全分开了。是两个不同的概念。

    >>> name = ur'| hf'

    File "<stdin>", line 1

    name = ur'| hf' ^

    SyntaxError: invalid syntax

    >>> name = ru'| hf'

    File "<stdin>", line 1

    name = ru'| hf' ^

    SyntaxError: invalid syntax

        字符串的常用操作:

        # 索引:

    >>> s

    'hello'

    >>> s[1]

    'e'

    >>> s.index(1)

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    TypeError: must be str, not int

    >>> s.index('1') # s 中没有'1'这个字符,报错

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    ValueError: substring not found

    >>> s.index('l') #

    2

        # 查找

    >>> s.find('e')

    1

    >>> s.find('i') # s中没有i这个字符,返回-1

    -1

    >>> s[1]

    'e'

        # 移除空白

    >>> s = " hello world "

    >>> s

    ' hello world '

    >>> s.strip()

    'hello world'

    >>> s

    ' hello world '

    >>> s.lstrip()

    'hello world '

    >>> s.rstrip()

    ' hello world'

    >>> s = "*****hello world*******"

    >>> s.strip('*')

    'hello world'

        # 长度

    >>> s

    '*****hello world*******'

    >>> len(s)

    23

        # 替换

    >>> s

    '*****hello world*******'

    >>> a = s.replace('*','') # 用空字符替换 *

    >>> a

    'hello world'

    >>> s2 = 'hi , how are you ?'

    >>> s2

    'hi , how are you ?'

    >>> s3 = s2.replace(' ','') # 用空字符替换空了一个字符的空格

    >>> s3

    'hi,howareyou?'

        切片:

    >>> len(s3)

    13

    >>>

    >>> s3

    'hi,howareyou?'

    >>> len(s3)

    13

    >>> s3[0:4]

    'hi,h'

    >>> s3[4:12]

    'owareyou'

    >>> s3[:]

    'hi,howareyou?'

    >>> s3[0:7:3]

    'hha'

    >>> s3[3:12:2]

    'hwryu'

    >>> s3[::2]

    'h,oaeo?'

    >>> s3[::-1]

    '?uoyerawoh,ih'

        字符串的工厂函数

    >>> dir(str)

    ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

        capitalize(self):首字母大写

        center(self,width,fillchar=None) 原来字符居中,不够用空格补全

        count(self,sub,start=None,end=None) 从一个范围内的统计某str出现的次数

        encode(self,endcoding='utf-8',errors='strict') encoding='utf-8'指定编码格式编码,如果出错默认报一个valueError,除非errors指定的是ignorereplcace ,返回值是bytes类型的数据

        endswith(self,suffix,start=None,end=None) 返回值是一个bool值,判断字符串的最后一个字符,如果是,返回true;不是返回false

    >>> s

    'hello'

    >>> s.endswith('o')

    True

    >>> s.endswith('h')

    False

        expandtabs(self,tabsize=8) 将字符串中包含的 转换成tabsize个空格

    >>> s='he llo'

    >>> s.expandtabs(tabsize=8)

    'he llo'

        find(self,sub,start=None,end=None) 返回值位int类型,查找字符串的某个字符的索引,正确:返回字符所在的索引值,错误:返回-1

    >>> s

    'he llo'

    >>> s.find('0')

    -1

    >>> s.find('o')

    5

        format(self,*args,**kwargs) 格式化输出

        第一种形式:

    >>> print('{0} {1} {0}'.format('a','b'))

    a b a

        第二种形式:()

    >>> print('{}{}{}'.format('a','c','b'))

    acb

        第三种形式:(format后面必须使用键值对的形式)

    >>> print('{name} {age}'.format(name='lzj',age=27))

    lzj 27

    >>> print('{name} {age}'.format('lzj',27))

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    KeyError: 'name'

        format_map(self,mapping)

    >>> name='xiaoming'

    >>> n=30

    >>> s = '{name} has {n} messages'

    >>> s.format_map(vars()) # 从已有的变量中找到name ,n 的变量

    'xiaoming has 30 messages'

        index(self,sub,start=None,end=None) 查询字符串的某个索引,查到了:返回对应的索引值,查不到就会报错

    >>> name

    'xiaoming'

    >>> name.index('e')

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    ValueError: substring not found

    >>> name.index('n')

    6

        isalnum(self) 至少一个字符,且都是字母或数字才返回True,判断一个字符串是否是由字母或数字组成,是:就返回true; 如果里面有特殊字符:返回false

    >>> name

    'xiaoming'

    >>> name.isalnum()

    True

    >>> name = '123xiaoming'

    >>> name.isalnum()

    True

    >>> name = '!@#123xiaoming'

    >>> name.isalnum()

    False

    >>> name.isalnum()

    True

        isalpha(self): 至少是一个字符,且都是字母才返回True ; 判断一个字符串是不是由字母组成的,是:就返回True;如果有数字,特殊字符就返回false

    >>> name

    '!@#123xiaoming'

    >>> name.isalpha()

    False

    >>> name='123xiaoming'

    >>> name.isalpha()

    False

    >>> name='xiaoming'

    >>> name.isalpha()

    True

        isdecimal(self) 判断一个字符串是不是由数字组成:是返回True如果 string 只包含十进制数字则返回 True 否则返回 False.

    >>> name

    '123'

    >>> name.isdecimal()

    True

    >>> name = 'asd'

    >>> name= '!@#'

    >>> name.isdecimal()

    False

        isidentifier(self): 方法用于判断字符串是否是有效的 Python 标识符,可用来判断变量名是否合法

    >>> name = 'lzj'

    >>> name.isidentifier()

    True

    >>> S.isdentifier(name)

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    NameError: name 'S' is not defined

    >>> name

    'lzj'

    >>> name.isidentifier()

    True

    >>> name = 123

    >>> name.isidentifier()

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    AttributeError: 'int' object has no attribute 'isidentifier'

    >>> name = 'afe'

    >>> name.isidentifier()

    True

        isdigit() 方法检测字符串是否只由数字组成。

    >>> name

    'afe'

    >>> name.isdigit()

    False

    >>> name = 123

    >>> name.isdigit()

    Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

    AttributeError: 'int' object has no attribute 'isdigit'

    >>> name = '123'

    >>> name.isdigit()

    True

    >>> name = '123lzj'

    >>> name.isdigit()

    False

        isnumeric() 如果 string 中只包含数字字符,则返回 True,否则返回 False

    >>> name

    '123lzj'

    >>> name.isnumeric()

    False

    >>> name = '123'

    >>> name.isnumeric()

    True

        title() 返回标题化的string,就是说所有的单词都是以大写开始,其它的全部是小写

    将字符串所有的单词首字母大写,如果字符串里面有数字,不管他

    >>> name

    '123'

    >>> name.title()

    '123'

    >>> name

    '123'

    >>> name= 'age old girl'

    >>> name.title()

    'Age Old Girl'

    >>> name = 'age 123 old girl'

    >>> name.title()

    'Age 123 Old Girl'

        swapcase() 字符串中的所有字母大小写反转

    >>> name

    'age 123 old girl'

    >>> name = name.title()

    >>> name

    'Age 123 Old Girl'

    >>> name.swapcase()

    'aGE 123 oLD gIRL'

        maketrans(self, *args, **kwargs) 返回一个映射的表

        translate(str,del='') 根据 str 给出的表(包含 256 个字符)转换 string 的字符,要过滤掉的字符放到 del 参数中

    >>> table = str.maketrans('hello','big S')

    >>> table

    {104: 98, 101: 105, 108: 32, 111: 83}

    >>> a = 'hello abc'

    >>> print(a.translate(table))

    bi S abc

        upper() 字符串的字母全部大写

        lower() 字符串的字母全部小写

    >>> a

    'hello abc'

    >>> b =a.upper()

    >>> b

    'HELLO ABC'

    >>> c = b.lower()

    >>> c

    'hello abc'

        zfill(width) 返回长度为 width 的字符串,原字符串 string 右对齐,前面填充0

    >>> a

    'hello abc'

    >>> a.zfill(20)

    '00000000000hello abc'

        split(self, /, sep=None, maxsplit=-1) str 为分隔符切片 string,如果 num 有指定值,则仅分隔 num+ 个子字符串

        splitlines([keepends]) 按照行(' ', ' ', ')分隔,返回一个包含各行作为元素的列表,如果参数 keepends False,不包含换行符,如果为 True,则保留换行符

    >>> help(str.split)

    Help on method_descriptor:

    split(self, /, sep=None, maxsplit=-1)

    Return a list of the words in the string, using sep as the delimiter string.

     

    sep

    The delimiter according which to split the string.

    None (the default value) means split according to any whitespace,

    and discard empty strings from the result.

    maxsplit

    Maximum number of splits to do.

    -1 (the default value) means no limit.

    >>> a

    'hello abc'

    >>> a = a + '123 lzj pwd cmd '

    >>> a

    'hello abc123 lzj pwd cmd '

    >>> b = a.split()

    >>> b

    ['hello', 'abc123', 'lzj', 'pwd', 'cmd']

    replace(old_str,new_str) 替换字符串的内容

    >>> a

    'hello abc123 lzj pwd cmd '

    >>> b = a.replace('l','mm')

    >>> b

    'hemmmmo abc123 mmzj pwd cmd '

        join(self, iterable) iterable 中所有的元素(的字符串表示)合并为一个新的字符串

    >>> a = ['lzj' , 'tom' , 'pwd']

    >>> a

    ['lzj', 'tom', 'pwd']

    >>> b = ''.join(a)

    >>> b

    'lzjtompwd'

    >>> c = '|'.join(a)

    >>> c

    'lzj|tom|pwd'

         

    菜鸟的自白
  • 相关阅读:
    MiracleSnow网页设计HTML5+CSS3+JS全套视频教程
    Java开发者应该列入年度计划的5件事
    大爱HTML5 9款超炫HTML5最新动画源码
    10个PHP代码片段
    斯坦福大学即将上线10门公开课
    如何成为一个偷懒又高效的Android开发人员
    github版本库使用详细教程
    PHP5中PDO的简单使用
    Github 已经托管超过 1000 万个项目库
    DIOCP转发型中间网关
  • 原文地址:https://www.cnblogs.com/lzjloveit/p/10582647.html
Copyright © 2011-2022 走看看