zoukankan      html  css  js  c++  java
  • 类型转换

    类型转换

    纯数字的字符串转成int

    res=int('100111')
    print(res,type(res))
    

    float类型转换

    res=float("3.1")
    print(res,type(res))
    

    字符串类型转换

    str可以把任意其他类型都转成字符串

    res=str({'a':1})
    print(res,type(res))
    

    使用:内置方法

    按索引取值(正向取+反向取) :只能取

    msg='hello world'
    正向取
    print(msg[0])
    print(msg[5])
    反向取
    print(msg[-1])
    
    只能取
    msg[0]='H'
    

    切片:索引的拓展应用,从一个大字符串中拷贝出一个子字符串

    msg='hello world'
    顾头不顾尾
    res=msg[0:5] #x
    print(res)
    print(msg)
    步长
    res=msg[0:5:2] # 0 2 4
    print(res) # hlo
    反向步长(了解)
    res=msg[5:0:-1]
    print(res) #" olle"
    msg='hello world'
    res=msg[:] # res=msg[0:11]
    print(res)
    res=msg[::-1] # 把字符串倒过来
    print(res)
    

    长度len

    msg='hello world'
    print(len(msg))
    

    成员运算in和not in

    判断一个子字符串是否存在于一个大字符串中

    print("alex" in "alex is sb")
    print("alex" not in "alex is sb")
    print(not "alex" in "alex is sb") # 不推荐使用
    

    移除字符串左右两侧的符号strip

    默认去掉的空格

    msg='      egon      '
    res=msg.strip()
    print(msg) # 不会改变原值
    print(res) # 是产生了新值
    

    默认去掉的空格

    msg='****egon****'
    print(msg.strip('*'))
    

    strip只取两边,不去中间

    # msg='****e*****gon****'
    # print(msg.strip('*'))
    

    ###切分split:把一个字符串按照某种分隔符进行切分,得到一个列表
    默认分隔符是空格

    info='egon 18 male'
    res=info.split()
    print(res)
    

    指定分隔符

    info='egon:18:male'
    res=info.split(':',1)
    print(res)
    

    strip,lstrip,rstrip

    print(msg.strip('*'))
    print(msg.lstrip('*'))
    print(msg.rstrip('*'))
    

    lower,upper

    msg='AbbbCCCC'
    print(msg.lower())
    print(msg.upper())
    

    startswith,endswith

    print("alex is sb".startswith("alex"))
    print("alex is sb".endswith('sb'))
    

    split,rsplit:将字符串切成列表

    info="egon:18:male"
    print(info.split(':',1)) # ["egon","18:male"]
    print(info.rsplit(':',1)) # ["egon:18","male"]
    

    join: 把列表拼接成字符串

    print(res)l=['egon', '18', 'male']
    res=l[0]+":"+l[1]+":"+l[2]
    res=":".join(l) # 按照某个分隔符号,把元素全为字符串的列表拼接成一个大字符串
    print(res)
    

    replace

    msg="you can you up no can no bb"
    print(msg.replace("you","YOU",))
    print(msg.replace("you","YOU",1))
    

    isdigit

    ** 判断字符串是否由纯数字组成**

    print('123'.isdigit())
    print('12.3'.isdigit())
    
    努力学习!
  • 相关阅读:
    preprocessing
    hist
    RabbitMQ
    线程池
    springmvc功能以及源码实现分析
    西瓜书第二章--模型评估与选择
    西瓜书第一章--绪论
    基于python的递归简述
    python小白学习之旅5
    python小白学习之旅4
  • 原文地址:https://www.cnblogs.com/Orange-YXH/p/13648086.html
Copyright © 2011-2022 走看看