python 数据类型的内置方法

发布时间 2023-11-30 16:27:19作者: -半城烟雨

python 数据类型的内置方法

#十进制数转为 其他进制
# print(bin(999))  # 0b1111100111 -- 0b 开头 最大只能到 1
# print(oct(999))  # 0o1747 -- 0o 开头就是八进制 --- 八进制
# print(hex(999))  # 0x3e7 -- 0x 开头就是十六进制 有英文字符的情况就是十六进制

# 其他进制 转为 十进制数
# print(int('0b1111100111', 2))
# print(int('0o1747', 8))
# print(int('0x3e7', 16))

字符串类型(str)

  • round() :取舍 四舍五入

  • isdigit(): 判定是否为整数

  • name[0]:字符串索引取值

  • join():拼接字符串 ‘*'.join(变量值)

  • 切片 也是 顾头不顾尾 [起始位置:想要的结束位置+1]

    word='hello_world'
    split_world=word[0:4+1]
    print(split_world)
    #hello
    
  • 切片+步长 word[0:4+1:2]

    word='hello_world'
    split_world=word[0:4+1:2]
    print(split_world)
    # 丛指定索引切到最后 --- [起始位置::]
    name_new_four = name[2::]
    print(name_new_four)
    #丛指定索引切到最后,加步长  --- [::步长]
    name_new_five = name[::2]
    print(name_new_five)
    
  • strip() : 去除首尾的空格

    name = '  asdasf   '
    print(name)
    print(name.strip())
    
  • 常用组合 input(' ').strip()

    name=input("请输入你的名字:>>>>").strip()
    print(name)
    
  • lstrip() 左空格 rstrip()右空格

    # 去除指定的字符
    name = '&&nancy&&'
    print(name.strip('&'))
    l -- left
    print(name.lstrip('&'))
    r -- right
    print(name.rstrip('&'))
    
  • 首尾字符判断

  • startswith():字符以什么开头

  • endswitch():字符以什么结尾

    # name = 'dream'
    #startswith : 判断当前字符以什么开头,返回布尔值
    print(name.startswith('w'))
    print(name.startswith('d'))
    # endswith : 判断当前字符以什么结尾,返回布尔值
    print(name.endswith('m'))
    print(name.endswith('d'))
    
  • replace():替换方法

    demo='I eat a hamburger'
    print(demo.replace('hamburger','hot dog'))
    
  • find():查找索引

  • index():索引值 ,索引第一个值

  • count():计数指定的元素个数

  • center():填充

    name = 'sadasfe'
    center : 填充 (基于你的字符串长度的宽度,填充的字符)
    #两侧填充,如果两侧个数不平衡的情况下就是,右多左少
    print(name.center(10, '-'))  # --dream---
    #ljust : 填充 (基于你的字符串长度的宽度,填充的字符)。
    填充指定字符在右侧
    print(name.ljust(10, '*'))  # dream*****
    #rjust : 填充 (基于你的字符串长度的宽度,填充的字符)。
    #填充指定字符在左侧
    print(name.rjust(10, '*'))  # *****dream
    #zfill : 填充 (基于你的字符串长度的宽度,填充的字符)。
    #使用 0 填充长度,填充在字符串左侧
    print(name.zfill(10))
    

列表类型(list)

  • list 可以强转字符串、元组、集合、字典

  • range():区间生成新列表

    print(list(range(1, 5)))  # [1, 2, 3, 4]
    
  • append():在结尾每次追加一个元素

    num_list = [1, 2, 3, 4, 5, 6]
    num_list.append(11) # 没有返回值 , 影响的是原来的列表
    print(num_list) # [1, 2, 3, 4, 5, 6, 11]
    
  • extend():可以添加多个元素到原来的末尾

    num_list = [1, 2, 3, 4, 5, 6]
    num_list.extend([99, 88, 77])
    print(num_list)
    
    
  • insert():按索引位置插值

    num_list = [1, 2, 3, 4, 5, 6]
    #insert : 按索引位置插值
    num_list.insert(1, 'b')
    print(num_list)
    
  • pop():去掉最后的元素 pop(1):去掉指定的元素

  • remove():删除指定位置元素

  • reverse():颠倒元素

    num_list = [1, 2, 3, 4, 5, 6]
    # reverse 颠倒元素,无返回值,影响到的是原来的列表
    num_list.reverse()
    print(num_list) #[6, 5, 4, 3, 2, 1]
    
  • sort():排序从小到大

  • #先排序,再反转
    num_list.sort(reverse=True)
    print(num_list)
    
  • 步长反转列表

    num_list=[1,3,4,5,7]
    print(num_list[::-1])