zoukankan      html  css  js  c++  java
  • Python-基础类型str

    字符串型

    用途:记录有描述性的状态,如名字,公司名称,家庭地址等
    定义方式:在引号(' '或者" "或者''' ''')包含一串字符

    s = 'hello'  # 与s = str('hello')等价,str()可以把任意类型转成字符串型
    

    常用操作及内置方法:
    以下所有方法必须掌握

    索引取值

    按索引取值(正取反取都可以),但不能改变值:

    s = 'hello'
    s[0] = 'h'
    s[-1] = 'o'
    

    切片

    切片(顾头不顾尾),切片属于拷贝操作,并不会修改原字符串

    s = "hello world"
    s1 = s[1:8:2]  # 完整切片语法[起始位置,结束为止,步长]
    print(s1)
    s2 = s[1:8]  # 省略步长,默认为1
    print(s2)
    s3 = s[:8:2]  # 省略起始位,默认0开始
    print(s3)
    s4 = s[::2]  # 省略起始位与结束位,默认从0到结束
    print(s4)
    s5 = s[::]  # 全省略,即打印一遍原字符串
    print(s5)
    s6 = s[:]  # 全省略的缩写方法
    print(s6)
    print(id(s) is id(s6))  
    """
    可以看到,当全省略后,s与s6的id是一样的,所以是同一个变量。
    但是在列表的切片中,是不同的两个列表。我们可以利用这一点,在某些情况下如我们想基于一个列表创建一个新列表并进行操作就可以这样操作
    """
    l = [1,2,3,4]
    l1 = l[:]
    print(l is l1)
    ------------------------------
    False
    

    计算长度

    计算长度 len()
    计算字符串有多少个字符,返回一个数字

    s = "hello world"  # 空格也算一个字符
    print(len(s))
    -------------------------
    11
    

    成员运算

    成员运算 in与not in
    判断某个字符串是否在被判断字符串中

    s = "hello world"
    print('o' in s)
    print('p' not in s)
    ------------------------------
    True
    True
    

    移除

    移除 strip()
    1.当使用strip()方法时,默认会消除字符串两边的空格,不会消除中间的空格

    s = '    hello world     '
    print(s.strip())
    ---------------------------
    hello world
    

    2.当strip()中加入字符,可移除字符串两边的指定字符

    s = '*****hello world****'
    print(s.strip('*'))
    -------------------------------------
    hello world
    

    3.当使用strip()时,若遇到的第一个字符没有指定在strip()的括号中,将会直接停住,不再移除其他字符,这就是为什么在字符串中间的空格不会被移除的原因。

    s = '  //**--he  llo--**//  '
    s1 = s.strip()
    print(s1)
    s2 = s.strip("/*-")
    print(s2)
    s3 = s.strip("/*- ")
    print(s3)
    s4 = '  he  llo  //  '
    s5 = s4.strip(' he')
    --------------------------------------------------------
    //**--he  llo--**//
      //**--he  llo--**//  
    he  llo
    llo  # 此时字符串中间的空格也被移除了,说明strip方法是遇到第一个不匹配的就停下
    

    切分

    切分 split()
    把字符串按照某个部分切成一个列表,默认分隔符为所有空字符,包括空格、换行( )、制表符( )等,k可指定分隔符

    s = "yang,123,456,789"
    s1 = s.split(',')
    print(s1)
    -------------------------
    ['yang', '123', '456', '789']
    

    split的可以指定切分几次,当不设置的时候,默认全部切分,工作原理是,先按照指定字符切割一次,将切分的左边存入列表,然后后边所有存入列表第二个位置,然后再从第二个位置切分,取出第二个切分对象放入列表第二个位置,右边新组成一个元素,再次存到列表第三个位置,以此类推,直到结束

    s = "yang,123,456,789"
    print(s.split(',',1))
    print(s.split(',',2))
    print(s.split(',',3))
    -----------------------------
    ['yang', '123,456,789']
    ['yang', '123', '456,789']
    ['yang', '123', '456', '789']
    

    可用join在拼回去

    s = "yang,123,456,789"
    s1 = s.split(',')
    print(s1,type(s1))
    s2 = ','.join(s1)  # 可用任意字符串拼接
    print(s2,type(s2))
    s3 = '|'.join(s1)
    print(s3,type(s3))
    --------------------
    ['yang', '123', '456', '789'] <class 'list'>
    yang,123,456,789 <class 'str'>
    yang|123|456|789 <class 'str'>
    

    循环

    可利用for循环,取出字符串的各个字符

    s = 'hello world'
    for i in s:
        print(i,end='_')  # 利用end='_'是为了使显示效果更明显
    ---------------------------------------
    h_e_l_l_o_ _w_o_r_l_d_
    

    lstrip,rstrip

    print("***hello***".strip("*"))
    print("***hello***".lstrip("*"))
    print("***hello***".rstrip("*"))
    ------------------------------------------------
    hello
    hello***
    ***hello
    

    lower,upper,swapcase

    lower():全小写

    upper():全大写

    swapcase():大小写反转

    msg = "AbCDEFGhigklmn"
    res = msg.lower()
    print(res)
    res = msg.upper()
    print(res)
    res=msg.swapcase()
    print(res)
    --------------------------------------------
    abcdefghigklmn
    ABCDEFGHIGKLMN
    aBcdefgHIGKLMN
    

    startswith,endswith

    startswith():判断是否以其中包含的字符串开头,返回布尔值

    endswith():判断是否以其中包含的字符串结尾,返回布尔值

    msg = "sb is lxx sb"
    print(msg.startswith("sb"))
    print(msg.endswith("b"))
    print(msg.endswith("c"))
    -----------------------------------------
    True
    True
    False
    

    rsplit

    与split相反,从右边向左切分

    userinfo="egon:123:18"
    # print(userinfo.split(":"))
    print(userinfo.split(":",1))
    print(userinfo.rsplit(":",1))
    ----------------------------------
    ['egon', '123:18']
    ['egon:123', '18']
    

    replace

    把字符串中的 old(旧字符串)替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

    基本格式

    str.replace(old, new[, max])
    
    msg = "***egon hello***"
    res=msg.replace('*','').replace(' ','')
    res=msg.strip('*').replace(' ','')
    print(res)
    
    s="lxx hahah wocale lxx sb 666"
    res=s.replace('lxx','sb',1)
    print(res)
    print(s)
    ---------------------------------------------------
    egonhello
    sb hahah wocale lxx sb 666
    lxx hahah wocale lxx sb 666
    

    占位符的三种玩法

    %s的方式
    name = "yang"
    age = 18
    res1="my name is %s my age is %s" % (name,age)
    print(res1)
    ----------------------------------------
    my name is yang my age is 18
    
    format的方式
    name = "yang"
    age = 18
    res1="my name is {} my age is {}".format(name,age)
    res2="{0}{1}{0}{1}".format(name,age)  # 按照索引
    res3="my name is {name} my age is {age}".format(age=18,name="yang")  # 关键字,此时age与name必须在后面再次申明
    print(res1)
    print(res2)
    print(res3)
    ----------------------------------------------------
    my name is yang my age is 18
    yang18yang18
    my name is yang my age is 18
    
    f''

    仅在python3中可以使用

    name = "yang"
    age = 18
    res1 = f"my name is {name} my age is {age}"
    print(res1)
    --------------------------------------------------
    my name is yang my age is 18
    
    #了解:f搭配{}可以执行字符串中的代码
    res=f'{len("hello")}'
    print(res)
    
    f'{print("hello")}'
    
    #f包含的字符串可以放到多行
    name = "yang"
    age = 18
    res1 = f"my name is {name} " 
           f"my age is {age}"
    
    #{}内不能有以及#
    
    print('胜率是 %s%%' %70)
    #了解:https://zhuanlan.zhihu.com/p/110406030
    

    find,rfind,index,rindex,count

    index与find的使用一样,不同在于find若未找到会返回-1,index未找到直接报错。尽量用find来操作,保护软件的稳定性。

    x = "hello egon egon egon"
    res=x.find("egon")
    print(res)
    res=x.find("egon123") # -1代表没有找到
    print(res)
    ----------------------------------
    6
    -1
    
    res=x.rfind("egon")
    print(res)
    ---------------------------
    16
    
    res=x.find("egon",0,3)
    print(res)
    ------------------------------
    -1
    
    res = x.index("egon123") # 找不到则报错
    print(res)
    ----------------------------------------------
    ValueError: substring not found
    

    center,ljust,rjust,zfill

    x = "yang"
    res=x.center(50,'*')
    print(res)
    -----------------------------------------------------------------
    ***********************yang***********************
    
    print(x.ljust(50,"*"))
    print(x.rjust(50,"*"))
    print(x.zfill(50))
    print(x.rjust(50,"0"))
    ----------------------------------------------------------------------------
    yang**********************************************
    **********************************************yang
    0000000000000000000000000000000000000000000000yang
    0000000000000000000000000000000000000000000000yang
    

    expandtabs

    expandtabs() 方法把字符串中的 tab 符号(' ')转为空格,tab 符号(' ')默认的空格数是 8。可以在其中添加参数,如expandtans(1)。

    从头开始数,数到第一个 正好为8个空格,不足则补空格,如果还有 ,接着从第一个 数到第二个 仍然为8个空格,以此类推直到最后一个 结束。

    print("hello	world".expandtabs())
    print("hi	world".expandtabs())
    print("abcdesghi	world".expandtabs())
    ------------------------------------
    hello   world  # hello有五个字符,所以填充三个空格
    hi      world  # hi有两个字符,所以填充留个空格
    abcdesghi       world  # 以八个字符为一组,此处a-h为八个字符,所以i填充七个空格
    

    captalize,swapcase,title

    print("hello world".capitalize())  # 使第一个字符大写
    print("hello world".title())  # 每个单词的首字母大写,若一些英文文章的题目有这方面的格式要求
    ---------------------------------
    Hello world
    Hello World
    

    is其他

    name='egon123'
    print(name.isalnum()) #字符串是否由字母或数字组成
    print(name.isalpha()) #字符串是否只由字母组成
    -------------------
    True
    False
    
    name="aaainputbbbbb"
    print(name.isidentifier()) # 判断字符串是有效标识符
    -------------------
    True
    
    name="abc123"
    print(name.islower())  # 判断字符串是否全小写,有数字不影响判断,只看字母
    print(name.isupper())  # 判断字符串是否全小写,有数字不影响判断,只看字母
    -----------------------
    True
    False
    
    
    string="     "
    print(string.isspace())  # 判断字符串是否全空格
    -----------------
    True
    
    
    name="My Name Is Egon"
    print(name.istitle())  # 判断字符串是否符合标题格式
    ----------------
    True
    

    is数字系列

    # 在python3中
    num1=b'4' #bytes
    num2=u'4' #unicode,python3中无需加u就是unicode
    num3='四' #中文数字
    num4='Ⅳ' #罗马数字
    
    #1、 isdigit判断是否为纯数字字符串(浮点型因为有小数点,不算纯数字)
    # bytes、unicode可判断为True,中文与罗马数字判断为False
    print(num1.isdigit())
    print(num2.isdigit())
    print(num3.isdigit())
    print(num4.isdigit())
    -------------------------------------
    True
    True
    False
    False
    
    #2、isnumeric检测变量是否为数字或数字字符串
    # unicode、中文数字、罗马数字判断为True,bytes类型无此方法
    # 所以num1.isnumeric()会直接报错
    print(num2.isnumeric())
    print(num3.isnumeric())
    print(num4.isnumeric())
    -----------------
    True
    True
    True
    
    
    #3、isdecimal 判断字符串是否只有十进制字符串组成这种方法只存在于unicode对象,注意:定义一个十进制字符串,只需要在字符串前添加 'u' 前缀即可。
    # bytes类型同样无此方法。
    print(num2.isdecimal())
    print(num3.isdecimal())
    print(num4.isdecimal())
    -----------------
    True
    False
    False
    

    字符串型总结

    1.存一个值
    2.有序
    3.不可变类型

  • 相关阅读:
    sh_09_字典的定义
    sh_08_格式化字符串
    sh_07_元组遍历
    sh_06_元组基本使用
    sh_05_列表遍历
    sh_04_列表排序
    sh_03_列表的数据统计
    图片懒加载
    UA池和ip代理池
    爬虫篇 --- 分布式爬虫
  • 原文地址:https://www.cnblogs.com/chiyun/p/14066215.html
Copyright © 2011-2022 走看看