zoukankan      html  css  js  c++  java
  • Python python 五种数据类型--字符串

    # python 字符串的初始化
    var1 = 'hello,world'
    
    # python 字符串为不可变类型
    var2= var1* 2
    print(var1) #hello,world
    print(var2) #hello,world hello,world
    
    # python 方法
    lenth = len(var1)
    print(lenth) #12
    
    res1 = var1.index('l') # 'l' 在 字符串上的下标,默认是第一个‘l’
    print(res1) #2
    
    res2 = var1.index('l',4) # 'l' 在字符串上的下标,从第4个下标开始找
    print(res2) #9
    
    res3 = var1.rindex('l')  # 反向寻找‘l’所在的下标
    print(res3) #9
    
    res4 = var1.count('l') # 统计‘l’在字符串中出现的次数,也可以添加参数start_index,end_index
    print(res4) #3
    
    res5 = var1[0] # 取下标为0的字符
    print(res5)#h
    
    res6 = var1[0:2] #取下标 【0,2)的字符
    print(res6)#he
    
    res7 = var1[0:6:2] #取下标【0,6)的字符,步长为2
    print(res7) #hlo
    
    res8 = var1[-1] #字符串最后一位的字符
    print(res8) #d
    
    res9 = var1[-2:] #取字符串最后2位
    print(res9) #ld
    
    var2 = "  Hello World "
    rest1 = var2.swapcase();# 大小写交换 swap 交换
    print(rest1) #hELLO wORLD
    
    rest2 = var2.strip() # 去除两边的空格,也可以是指定字符
    print(rest2) #Hello World
    
    rest3 = var2.rstrip()
    print(rest3) #  Hello World 只去除右边的空格
    
    rest4 = var2.lstrip()
    print(rest4) #Hello World  只去除左边的空格
    
    rest5 = var2.upper() #全部转换大写
    print(rest5)#  HELLO WORLD
    
    rest6 = var2.lower();#全部转换小写
    print(rest6)#  hello world
    
    rest7 = var2.find('p') # 'p' 在 字符串上的下标,默认是第一个‘p’,找不到-1
    print(rest7)#-1
    
    rest8 = var2.index('') # 'l' 在 字符串上的下标,默认是第一个‘l’,找不到报错 ValueError: substring not found
    print(rest8)
    
    
    var3 = 'helloWorld'
    re1 = var3.capitalize() # 首字母大写,如果第一个字符是字母
    print(re1)
    
    re2 = var3.center(20) #20 个字符的情况下,字符串左右对称
    print(re2)#     helloWorld
    
    re3 = var3.split('W') # split
    print(re3)
    
    #Python casefold() 方法是Python3.3版本之后引入的,其效果和 lower() 方法非常相似,都可以转换字符串中所有大写字符为小写。
    #两者的区别是:lower() 方法只对ASCII编码,也就是‘A-Z’有效,对于其他语言(非汉语或英文)中把大写转换为小写的情况只能用 casefold() 方法。
    re4 = var3.casefold();
    print(re4)
    
    var4 = '{0}{1},Hello Python'
    re5 = var4.format('Hello','World');
    print(re5)#HelloWorld,Hello Python
  • 相关阅读:
    hyper虚拟机下对centos进行动态扩容
    《C#高级编程第七版》多线程之Events
    借鉴StanZhai核心代码,写了个博客园采集器
    文档转换之PDF转换为HTML
    书香电子书下载地址分析器
    c#常用类库及资源
    iis7.5 配置伪静态
    根据枚举类型获取描述
    从客户端检测到有潜在危险的Request.Form值
    Sql行列转换
  • 原文地址:https://www.cnblogs.com/pickKnow/p/10874516.html
Copyright © 2011-2022 走看看