zoukankan      html  css  js  c++  java
  • 数据类型的内置方法

    曾经的我意气风发,做事放荡不羁,常常把人看扁,现在不一样了,长大了,已经根本不把别人放在眼里了。

    开个玩笑,其实是被社会磨平了棱角。

    每天就这个状态

    像个卷帘大将一样。

    好的那就开始今天的打气流程!

    今日洗脑金句: 学习就像人生,要好好经历,加油,你要保持善良,也要带点锋芒!

    数字类型内置方法

    like 大家都 know 的,数字类型又分为整型和浮点型。

    来我先带各位憨憨回顾一下整型和浮点型的用途以及定义 ↓

    一、整型内置方法(int)

    1.用途:年龄、号码、等级

    2.定义:可以使用 int() 方法将纯数字的字符串转为十进制的整型

    age = 19  # age = int(10)
    print(type(age))
    

    <class 'int'>

    需要注意一下的是下面这个,因为我挂了一次

    x = int('11.1')  # 报错
    print(x)
    

    注意哦,这里会报错,这究竟是为什么呢???

    我是这么理解的,里面确实是个数字是吧,但是!

    这是个字符串类型的数据,你让int方法怎么把 '.' 给转化成整型呢,很明显不能,所以这里会报错,可能你们会有别的理解,可以来告诉我,反正我也不听。

    3.常用操作就是算术运算+比较运算 这么简单。

    长整型就不说了,他只存在与python2中,python3已经没这玩意儿了。统一为 int 型。

    1.1 可变or不可变

    一句巨他妈重要的话,“id相同,变量值一定相同,变量值相同,id不一定相同。“

    什么叫可变类数据类型,就是id不变值可变,就是在原值基础上修改,则为可变数据类型 ;反之,值变id也变,就是重新申请一个空间放入新值,这就是不可变数据类型。 你当然听不明白,看完栗子你就明白了。

    age = 19
    print(f'first:{id(age)}')
    age = 20
    print(f'second:{id(age)}')
    

    first:4384901776
    second:4384901808

    看到了吗,我们改变了age的变量值,发现打印出来的id值变了,说明什么,age已经不是指向 原来的 19 那块地址空间了,而是指向了重新开辟出来的 20 的地址空间,所以整型很明显是不可变数据类型。

    二、浮点型内置方法(float)

    1.用途:薪资、身高、体重

    2.定义:可以使用float()方法将纯数字的字符串转为浮点型数字。

    x = float('111')
    print(x)
    print(type(x))
    

    111.0
    <class 'float'>

    a=1.1
    b=1
    print(float(b))
    print(int(a))
    

    1.0
    1

    诶!看见了没,这里的1.1可以用int方法来转换,为什么呢,因为这里的1.1他是数字类型的呀,转为整型之后就会把小数点和后面的全缪莎掉。

    3.常用操作+内置方法:算术运算+比较运算

    4.存一个值or多个值:一个值

    5.有序or无序:和整型一样,都是没有有序无序这种说法的。

    6.可变or不可变:和整形一样,都是不可变数据类型。

    字符串类型内置方法

    打字太累了,用一下CV架构

    一、字符串类型内置方法(str)

    1.用途:描述性质的东西,如人的名字、单个爱好、地址、国家等

    2.定义:使用''、""、''''''、""""""包裹的的一串字符

    • u'unicode': unicode编码的字符串
    • b'101': 二进制编码的字符串
    • r' ': 原生字符串,也就是说' '这是普通的两个字符,并没有换行的意思
    name = 'nick'  # name =str('nick')
    s1 = str(1.1)
    s2 = str([1, 2, 3])
    
    print(f's1:{s1}, type:{type(s1)}')
    print(f's2:{s2}, type:{type(s2)}')
    

    s1:1.1, type:<class 'str'>
    s2:[1, 2, 3], type:<class 'str'>

    简单讲一下 r 的作用,你输出的时候要换行就输入 是吧,可是如果你要输出的字符串内容之中有 呢,这个时候就需要在字符串前面加上一个 r ,使他变为原生字符串。

    1.1优先掌握的方法

    优先掌握么就是很重要啦,靓仔。

    1. 按索引取值
    2. 切片
    3. 长度len
    4. 成员运算in|not in
    5. 移除空白strip
    6. 切分split
    7. 循环

    CV大法好啊!!!!!!

    1.按索引取值(只可取不可改变)

    # str索引取值
    msg = 'hello nick'
    #      0123456789  # 索引序号
    
    print(f'索引为6: {msg[6]}')
    print(f'索引为-3: {msg[-3]}')
    索引为6: n
    索引为-3: i
    

    2.切片(顾头不顾尾,步长)

    # 索引切片
    msg = 'hello nick'
    #      0123456789  # 索引序号
    
    print(f'切片3-最后: {msg[3:]}')
    print(f'切片3-8: {msg[3:8]}')
    print(f'切片3-8,步长为2: {msg[3:8:2]}')
    print(f'切片3-最后,步长为2: {msg[3::2]}')
    
    # 了解,步长为正从左到右;步长为负从右到左
    print('
    **了解知识点**')
    print(f'切片所有: {msg[:]}')
    print(f'反转所有: {msg[::-1]}')
    print(f'切片-5--2: {msg[-5:-2:1]}')
    print(f'切片-2--5: {msg[-2:-5:-1]}')
    切片3-最后: lo nick
    切片3-8: lo ni
    切片3-8,步长为2: l i
    切片3-最后,步长为2: l ik
    
    **了解知识点**
    切片所有: hello nick
    反转所有: kcin olleh
    切片-5--2:  ni
    切片-2--5: cin
    

    3.长度len

    # str长度
    msg = 'hello nick'
    
    print(len(msg))
    10
    

    4.成员运算in和not in

    # str成员运算
    msg = 'my name is nick, nick handsome'
    
    print(f"'nick' in msg: {'nick' in msg}")
    print(f"'jason' not in msg: {'jason' not in msg}")
    print(f"not 'jason' in msg: {not 'jason' in msg}")
    'nick' in msg: True
    'jason' not in msg: True
    not 'jason' in msg: True
    

    5.移除空白strip()

    # str移除空白strip()
    name = '&&&n ick'
    
    print(f"name.strip('&'): {name.strip('&')}")  # strip()默认为‘ ’,并且不修改原值,新创建空间
    print(f"name: {name}")
    
    # strip()应用场景
    pwd = input('password: ')  # 用户可能会手抖输入空格
    if pwd.strip() == '123':
        print('密码输入成功')
    
    print(f"'*-& nick+'.strip('*-& +'): {'*-& nick+'.strip('*-& +')}")
    name.strip('&'): n ick
    name: &&&n ick
    password: 123   
    密码输入成功
    '*-& nick+'.strip('*-& +'): nick
    

    我前几天在预习的时候,看到切片和split()方法,踩了一些坑,不过今天学了以后发现大部分都是自己问题,可以看一下这一片博客体会一下我当时的体验。

    博客传送门

    6.切分split

    # str切分split
    info = 'nick:male:19'
    info_list1 = info.split(':')
    info_list2 = info.split(':', 1)
    
    print(f'info_list1:{info_list1}')
    print(f'info_list2:{info_list2}')
    info_list1:['nick', 'male', '19']
    info_list2:['nick', 'male:19']
    

    7.循环

    msg = 'hello nick'
    
    for i in msg:
        print(i)
    h
    e
    l
    l
    o
     
    n
    i
    c
    k
    

    1.2 需要掌握(**)

    1.lstrip()和rstrip()

    # str之lstrip()和rstrip()
    name = '&&nick&&'
    
    print(f"nick.lstrip('&'): {name.lstrip('&')}")
    print(f"nick.rstrip('&'): {name.rstrip('&')}")
    nick.lstrip('&'): nick&&
    nick.rstrip('&'): &&nick
    

    2.lower()和upper()

    # str之lower()和upper()
    name = 'Nick Chen'
    
    print(f"name.upper(): {name.lower()}")
    print(f"name.upper(): {name.upper()}")
    name.upper(): nick chen
    name.upper(): NICK CHEN
    

    3.startswith()和endswith()

    # str之startswith()和endswith()
    name = 'Nick Chen'
    
    print(f"name.startswith('Nick'): {name.startswith('Nick')}")
    print(f"name.endswith('chen'): {name.endswith('chen')}")
    name.startswith('Nick'): True
    name.endswith('chen'): False
    

    4.rsplit()

    # str之rsplit()
    info = 'nick:male:19'
    
    print(f"info.rsplit(':', 1): {info.rsplit(':', 1)}")  # 从右开始切割
    info.rsplit(':', 1): ['nick:male', '19']
    

    5.join()

    lis = [1,2,'19']
    print(f"':'.join(lis): {':'.join(lis)}")  # 报错,数字不可和字符串拼接
    # str之join()
    lis = ['nick', 'male', '19']
    
    print(f"':'.join(lis): {':'.join(lis)}")
    ':'.join(lis): nick:male:19
    

    6.replace()

    # str值replace()
    name = 'nick shuai'
    
    print(f"name.replace('shuai','handsome'): {name.replace('shuai','handsome')}")
    name.replace('shuai','handsome'): nick handsome
    

    7.isdigit()

    # str值isdigit()
    salary = '111'
    print(salary.isdigit())  # True
    
    salary = '111.1'
    print(salary.isdigit())  # False
    True
    False
    # str之isdigit()应用场景
    age = input('age: ')
    if age.isdigit():
        age = int(age)
    
        if age < 18:
            print('小姐姐')
        else:
            print('阿姨好')
    else:
        print(f'你的年龄能是这个{age}?')
    age: 逗你玩?
    你的年龄能是这个逗你玩??
    

    1.3 其他操作(**)

    这些只需要了解一下就好了,不用去死磕,前面的那些方法才是需要死磕的,别搞错了,到时候舍本逐末损失最大的还是你哦。

    1.find()、rfind()、index()、rindex()、count()

    # str之find()、rfind()、index()、rindex()、count()
    msg = 'my name is tank, tank shi sb, hha'
    
    print(f"msg.find('tank'): {msg.find('tank')}")  # 找不到返回-1
    print(f"msg.find('tank',0,3): {msg.find('tank',0,3)}")
    print(f"msg.rfind('tank'): {msg.rfind('tank')}")  # 找不到返回-1
    print(f"msg.index('tank'): {msg.index('tank')}")  # 找不到报错
    print(f"msg.rindex('tank'): {msg.rindex('tank')}")  # 找不到报错
          
    
    print(f"msg.count('tank'): {msg.count('tank')}")
    msg.find('tank'): 11
    msg.find('tank',0,3): -1
    msg.rfind('tank'): 17
    msg.index('tank'): 11
    msg.rindex('tank'): 17
    msg.count('tank'): 2
    

    2.center()、ljust()、rjust()、zfill()

    # str之center()、ljust()、rjust()、zfill()
    print(f"'info nick'.center(50,'*'): {'info nick'.center(50,'*')}")
    print(f"'info nick'.ljust(50,'*'): {'info nick'.ljust(50,'*')}")
    print(f"'info nick'.rjust(50,'*'): {'info nick'.rjust(50,'*')}")
    print(f"'info nick'.zfill(50): {'info nick'.zfill(50)}")  # 默认用0填充
    'info nick'.center(50,'*'): ********************info nick*********************
    'info nick'.ljust(50,'*'): info nick*****************************************
    'info nick'.rjust(50,'*'): *****************************************info nick
    'info nick'.zfill(50): 00000000000000000000000000000000000000000info nick
    

    3.expandtabs()

    # str之expandtabs()
    print(f"a\tb\tc: %s"%('a	b	c	'))  # 默认制表符8个空格
    print(f"'a\tb\tc'.expandtabs(32): %s"%('a	b	c	'.expandtabs(32)))
    a	b	c: a  b   c   
    'a	b	c'.expandtabs(32): a                               b                               c                               
    

    4.captalize()、swapcase()、title()

    # str之captalize()、swapcase()、title()
    name = 'nick handsome sWAPCASE'
    
    print(f"name.capitalize(): {name.capitalize()}")
    print(f"name.swapcase(): {name.swapcase()}")  # 大小写互转
    print(f"name.title(): {name.title()}")
    name.capitalize(): Nick handsome swapcase
    name.swapcase(): NICK HANDSOME Swapcase
    name.title(): Nick Handsome Swapcase
    

    5.is数字系列(只是为了告诉你,判断是否为数字时除了中文数字以后使用isdigit()即可)

    • isdecimal(): 检查字符串是否值包含十进制字符,如果是返回True,否则返回False。
    • isdigit(): 如果字符串只包含数字则返回True,否则返回False。
    • isnumeric(): 如果字符串中只包含数字字符,则返回True,否则返回False。
    num = "1"  #unicode
    num.isdigit()   # True
    num.isdecimal() # True
    num.isnumeric() # True
    
    num = "1" # 全角
    num.isdigit()   # True
    num.isdecimal() # True
    num.isnumeric() # True
    
    num = b"1" # byte
    num.isdigit()   # True
    num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
    num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'
    
    num = "IV" # 罗马数字
    num.isdigit()   # True
    num.isdecimal() # False
    num.isnumeric() # True
    
    num = "四" # 汉字
    num.isdigit()   # False
    num.isdecimal() # False
    num.isnumeric() # True
    
    ===================
    isdigit()
    True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
    False: 汉字数字
    Error: 无
    
    isdecimal()
    True: Unicode数字,全角数字(双字节)
    False: 罗马数字,汉字数字
    Error: byte数字(单字节)
    
    isnumeric()
    True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
    False: 无
    Error: byte数字(单字节)
    
    ================
    import unicodedata
    
    unicodedata.digit("2")   # 2
    unicodedata.decimal("2") # 2
    unicodedata.numeric("2") # 2.0
    
    unicodedata.digit("2")   # 2
    unicodedata.decimal("2") # 2
    unicodedata.numeric("2") # 2.0
    
    unicodedata.digit(b"3")   # TypeError: must be str, not bytes
    unicodedata.decimal(b"3") # TypeError: must be str, not bytes
    unicodedata.numeric(b"3") # TypeError: must be str, not bytes
    
    unicodedata.digit("Ⅷ")   # ValueError: not a digit
    unicodedata.decimal("Ⅷ") # ValueError: not a decimal
    unicodedata.numeric("Ⅷ") # 8.0
    
    unicodedata.digit("四")   # ValueError: not a digit
    unicodedata.decimal("四") # ValueError: not a decimal
    unicodedata.numeric("四") # 4.0
    
    #"〇","零","一","壱","二","弐","三","参","四","五","六","七","八","九","十","廿","卅","卌","百","千","万","万","亿"
    

    6.is其他

    • isalnum(): 如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False。
    • isalpha(): 如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False。
    • islower(): 如果字符串中只包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True,否则返回False。
    • isspace(): 如果字符串中只包含空白,则返回True,否则返回False
    • isupper(): 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回True,否则返回False。
    • istitle(): 如果字符串是标题类型的(见title()),则返回True,否则返回False。

    4.存一个值or多个值:一个值

    5.有序or无序:只要是有索引的,都是有序的,因此字符串是有序的。

    name = 'nick'
    print(f'first:{id(name)}')
    name = 'nick handsome'
    print(f'second:{id(name)}')
    first:4377100160
    second:4377841264
    

    6.可变or不可变:不可变数据类型

    CV一时爽,一直CV一直爽!

    好了好了,今天的内容就这么多了,就讲到这里了。

  • 相关阅读:
    hdu1285 确定比赛名次(拓扑排序多种方法)
    软件配置管理中的SVN
    Maven实战(插件管理)
    oracle 数据库中,应用程序里的连接探測语句的正确使用
    2014百度之星资格赛第四题
    android制作闪动的红心
    程序猿生存定律-借势的价值与力量
    [SPOJ VLATTICE]Visible Lattice Points 数论 莫比乌斯反演
    机器学习:神经网络之表达
    【JavaScript】在同一个网页中实现多个JavaScript特效
  • 原文地址:https://www.cnblogs.com/chanyuli/p/11290540.html
Copyright © 2011-2022 走看看