zoukankan      html  css  js  c++  java
  • Python入门day08——基本数据类型之字符串及其内置方法

    基本数据类型之字符串及其内置方法

    1、作用
    2、定义
    msg='hello' # msg=str('msg')
    print(type(msg))
    
    3、类型转换
    str可以把任意其他类型都转成字符串
    
    res=str({'a':1})
    print(res,type(res))
    
    4、使用:内置方法
    4.1 优先掌握

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

    msg='hello world'
    
    # 正向取
    
    print(msg[0]) # h
    print(msg[6]) # w
    
    # 反向取
    
    print(msg[-1]) # d
    
    # 只能取,不能改
    
    msg[0]='H' # TypeError: 'str' object does not support item assignment
    

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

    msg='hello world'
    
    # 顾头不顾尾
    
    res=msg[0:5] #从下标0(也就是第1个字符)开始取,取到下标5-1(第5个字符),空格占1个字符串
    print(res) # hello
    print(msg) # hello world
    
    # 步长
    
    res=msg[0:5:2] # 从下标0(也就是第1个字符)开始取,取到下标5-1(第5个字符),步长为2
    print(res) # hlo
    
    # 反向步长(了解)
    
    res=msg[5:0:-1] # 从下标5(也就是第6个字符)开始取,取到下标0+1(第2个字符),步长为-1
    print(res) #" olle"
    
    # 正常取值
    
    msg='hello world'
    res=msg[:] # res=msg[0:11]  
    print(res)
    
    # 倒序取值
    
    res=msg[::-1] # 把字符串倒过来
    print(res) # dlrow olleh
    

    4.1.3长度len

    msg='hello world'
    print(len(msg),typelen(msg)) # 11 <class 'int'>  11就是该字符串的长度,类型为整形int
    

    4.1.4成员运算in和not in

    # 判断一个子字符串是否存在于一个大字符串中
    
    print("alex" in "alex is sb") # True
    print("alex" not in "alex is sb") # False
    print(not "alex" in "alex is sb") # Fal  不推荐使用
    

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

    # 默认去掉的空格是
    
    msg='      egon      '
    res=msg.strip() # 去掉两边的空格
    print(msg) # 不会改变原值       egon      
    print(res) # 是产生了新值 egon
    
    # 可以去掉指定的字符
    
    msg='****egon****'
    print(msg.strip('*')) # egon
    
    msg='**/*=-**egon**-=()**'
    print(msg.strip('*/-=()')) # egon 
    
    # 了解:strip只去两边,不去中间
    
    msg='****e*****gon****'
    print(msg.strip('*')) # e*****gon
    
    # 应用
    inp_user=input('your name>>: ').strip() # inp_user=" egon"
    inp_pwd=input('your password>>: ').strip()
    if inp_user == 'egon' and inp_pwd == '123':
        print('登录成功')
    else:
        print('账号密码错误')
    

    4.1.6、切分split:把一个字符串按照某种分隔符进行切分,得到一个列表

    # 默认分隔符是空格
    
    info='egon 18 male'
    res=info.split()
    print(res) # ['egon', '18', 'male']
    
    # 可以指定分隔符
    
    info='egon:18:male'
    res=info.split(':')
    print(res) # ['egon', '18', 'male']
    
    # 指定分隔次数(了解)
    
    info='egon:18:male'
    res=info.split(':',0) # 指定分隔次数为0 就是不分割
    print(res) # ['egon:18:male']
    
    info='egon:18:male'
    res=info.split(':',1)
    print(res) # ['egon', '18:male']
    

    4.1.7循环

    info='egon'
    for x in info:
        print(x)
        
    # 结果
    e
    g
    o
    n
    
    4.2 需要掌握

    4.2.1

    strip:移除两边的指定符号

    lstrip:移除左边的指定符号

    rstrip:移除右边的指定符号

    msg='***egon****'
    print(msg.strip('*')) # egon         
    print(msg.lstrip('*')) # egon****    
    print(msg.rstrip('*')) # ***egon     
    

    4.2.2

    lower:r把字符串中所有字母全部小写

    uppe:把字符串中所有字母全部大写

    msg='AbbbCCCC'
    print(msg.lower()) # abbbcccc        
    print(msg.upper()) # ABBBCCCC 
    

    4.2.3

    startswith:用于判断一段字符串是否以某段字符或者某个字符串开头

    endswith:用于判断一段字符串是否以某段字符或者某个字符串结尾

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

    4.2.4

    format

    4.2.5

    split:将字符串切成列表

    rsplit:将字符串从右开始切成列表

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

    4.2.6

    join::把列表拼接成字符串

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

    4.2.7

    replace:替换

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

    4.2.8

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

    print('123'.isdigit())
    print('12.3'.isdigit())
    
    age=input('请输入你的年龄:').strip()
    if age.isdigit():
        age=int(age) # int("abbab")
        if age > 18:
            print('猜大了')
        elif age < 18:
            print('猜小了')
        else:
            print('才最了')
    else:
        print('必须输入数字,傻子')
    
    4.3了解

    4.3.1find,rfind,index,rindex,count

    msg='hello egon hahaha'
    
    # 找到返回起始索引
    
    print(msg.find('e')) # 1返回要查找的字符串在大字符串中的起始索引
    print(msg.find('egon')) # 6
    print(msg.index('e')) # 1
    print(msg.index('egon')) # 6
    
    # 找不到结果
    print(msg.find('xxx')) # -1,代表找不到
    print(msg.index('xxx')) # 抛出异常
    
    msg='hello egon hahaha egon、 egon' 
    print(msg.count('egon')) # 3 字符串中含有egon的个数
    

    4.3.2center,ljust,rjust,zfill

    print('egon'.center(10,'*')) # ***egon***   *填充居中
    print('egon'.ljust(10,'*')) # egon******    *填充左对齐
    print('egon'.rjust(10,'*')) # ******egon    *填充右对齐
    print('egon'.zfill(10)) # 000000egon        用0填充,默认右对齐
    
    4.3.3、expandtabs
    
    msg='hello	world'
    print(msg.expandtabs(2)) # hello world  设置制表符代表的空格数为2
    

    4.3.4、captalize,swapcase,title

    print("hello world egon".capitalize()) # Hello world egon 字符串首字母大写
    print("Hello WorLd EGon".swapcase()) # hELLO wORlD egON 大小写互换
    print("hello world egon".title()) # Hello World Egon 单词首字母大写
    

    4.3.5、is数字系列

    num1=b'4' #bytes
    num2=u'4' #unicode,python3中无需加u就是unicode
    num3='四' #中文数字
    num4='Ⅳ' #罗马数字
    
    # isdigit只能识别:num1、num2
    
    print(num1.isdigit()) # True
    print(num2.isdigit()) # True
    print(num3.isdigit()) # False
    print(num4.isdigit()) # False
    
    # isnumberic可以识别:num2、num3、num4
    
    print(num2.isnumeric()) # True
    print(num3.isnumeric()) # True
    print(num4.isnumeric()) # True
    
    # isdecimal只能识别:num2
    
    print(num2.isdecimal()) # True
    print(num3.isdecimal()) # False
    print(num4.isdecimal()) # False
    

    4.3.6、is其他

    print('abc'.islower()) # True
    print('ABC'.isupper()) # True
    print('Hello World'.istitle()) # True
    print('123123aadsf'.isalnum()) # 字符串由字母或数字组成结果为True
    print('ad'.isalpha()) # 字符串由由字母组成结果为True
    print('     '.isspace()) # 字符串由空格组成结果为True
    print('print'.isidentifier()) # True 如果字符串仅包含字母数字字母(a-z)和(0-9)或下划线(_),则该字符串被视为有效标识符。有效的标识符不能以数字开头或包含任何空格
    print('age_of_egon'.isidentifier()) # True
    print('1age_of_egon'.isidentifier()) # False
    
  • 相关阅读:
    AtCoder Grand Contest 031
    CF1010D Mars rover
    51Nod 1317 相似字符串对
    upd
    查漏补缺——字符串www.qq.com所有非空子串
    c语言查漏补缺——Win32环境下动态链接库(DLL)编程原理
    编程——二维矩阵中1所构成的块个数(孤岛问题)
    使用Windows自带远程桌面应用连接CentOS8远程桌面
    ZeroTier + NoMachine
    WinPE装入硬盘做应急系统教程
  • 原文地址:https://www.cnblogs.com/yding/p/12458371.html
Copyright © 2011-2022 走看看