zoukankan      html  css  js  c++  java
  • python基础之字符串切片&操作方法

    1.字符换的定义:

    字符串或串(String)是由数字、字母、下划线组成的一串字符

     

     2.字符串操作

    字符串取值:

    str = "hello,world"
    print(str[0]) #取字符串的第一个字符
    print(str[1:11:3]) #取字符串索引1~11的数据,不包含结尾数据,步长为3(每隔3位取一个数)
    #输出结果:eood
    print(len(str)) #打印字符串的长度
    #输出结果:11
    print(str[ : : ]) #正序
    #输出结果:hello,world
    print(str[: : -1])   #倒序
    #输出结果:dlrow,olleh
    index=len(str)
    print(str[:index])  #字符串原样输出
    #输出结果:hello,world

    字符串其他的使用方法:

    #字符串操作
    a = "EEDJJJKJKEJ"
    print(a.count("J"))  #统计字符串中子字符串的个数
    #运行结果:5
    print(a.replace("E","0")) #替换字符串中的子字符串(old,new)
    #运行结果:00DJJJKJK0J
    print(a.lower()) #将字符串切换为小写,upper()切换大写
    #运行结果:edjjjkjkej
    print(a.index("J")) #取出第一个子字符串所在的索引
    #运行结果:3
    print(a.index("J",6)) #查询子字符串的角标,(”子字符串“,从当前索引开始)
    ##运行结果:7

     字符串的切割、拼接:

    s = '010-888-888-888'
    a = s.split("-") # 去掉s中的'-'
    print(a)
    #运行结果:['010', '888', '888', '888']
    b = "".join(a) #把列表中的数据链接成字符串
    print(b) 
    #运行结果:010888888888

    3.字符串格式化输出:

    三种方式:

    1.占位符方式输出:

     2.format方式(主流):

    name = "python"
    str = "hello {}".format(name)
    print(str)
    stra = "hello {},我叫{},性别{}".format(name,"chenran","") #从左到右输出
    print(stra)
    strb = "hello {2},我叫{1},性别{0}".format(name,"chenran","") #指定顺序输出
    print(strb)
    
    #运行结果为:
    hello python
    hello python,我叫chenran,性别男
    hello 男,我叫chenran,性别python

    3.f表达式:

    name = "python"
    strc = f"hello {name}"
    print(strc)
    运行结果:hello python
  • 相关阅读:
    Luogu P2391 白雪皑皑 && BZOJ 2054: 疯狂的馒头 并查集
    Luogu P3391 文艺平衡树(Splay or FHQ Treap)
    [笔记] 平衡树合集(Treap,Splay,替罪羊,FHQ Treap)
    P1353_[USACO08JAN]跑步Running 我死了。。。
    Luogu P1436 棋盘分割 暴力DP
    Luogu P1131 [ZJOI2007]时态同步 树形DP
    Luogu P1282 多米诺骨牌 DP。。背包?
    Luogu P1273 有线电视网 树形DP
    Luogu P1272 重建道路 树形DP
    Luogu P1156 垃圾陷阱 DP
  • 原文地址:https://www.cnblogs.com/crdhm12040605/p/15088048.html
Copyright © 2011-2022 走看看