python2之字符串操作

    更新一篇python字符串操作函数,未经允许切勿擅自转载。
  1. 字符串拼接:a+b
    代码:
    a = "woshi"
    b = "carcar96"
    
    print a+b                #方法1
    print "==%s=="%(a+b)     #方法2
    运行结果:

  2. 获取字符串长度:len(str)
    结果:
    str = "woshiasddscv"
    print(len(str))
    运行结果:12
  3. 获取字符串的第几个:str[i]
    代码:
    str = "woshiasddscv"
    print(str[0])
    运行结果:w
  4. 获取字符串的最后一个
    代码:
    str = "woshiasddscv"
    print(str[-1])
    print(str[len(str)-1])
    运行结果:

  5. 字符串切片:获取字符串中的第a个到第b个,但不包括第b个,c是步长(默认1)   str[a:b:c]
    代码:
    str = "woshiasddscv"
    print str[2:4]  #sh
    print str[2:-1] #shiasddsc
    print str[2:]   #shiasddscv
    print str[2:-1:2] #sisdc
    运行结果:

  6. 字符串倒序
    代码:
    str = "woshiasddscv"
    print str[-1::-1]   #vcsddsaihsow
    print str[::-1]     #vcsddsaihsow
    
    运行结果:

  7. 查找字符串,返回查找到的第一个目标下标,找不到返回-1:str.find("s")
    代码:
    str = "woshiasddscv"
    print str.find("s") #2
    print str.find("gg") #-1
    运行结果:

  8. 统计字符串中,某字符出现的次数:str.count("s")
    代码:
    str = "woshiasddscv"
    print str.count("s") #3
    print str.count("gg") #0
    运行结果:

  9. 字符串替换:str.replace(目标字符,替换成的字符)
    代码:
    str = "woshiasddscv"
    print str.replace("s","S")  #woShiaSddScv
    print str   #不变
    print str.replace("s","S",1)  #woShiasddscv
    print str.replace("s","S",2)  #woShiaSddscv
    运行结果:

  10. 字符串分割:str.split("s")
    代码:
    str = "woshiasddscv"
    print str.split("s")    #['wo', 'hia', 'dd', 'cv']
    运行结果:['wo', 'hia', 'dd', 'cv']
  11. 字符串全部变小写:str.lower()
    代码:
    str = "HhnuhHUJHfgt"
    print str.lower()  #hhnuhhujhfgt
    运行结果:hhnuhhujhfgt
  12. 字符串全部变大写:str.upper()
    代码:
    str = "HhnuhHUJHfgt"
    print str.upper()  #HHNUHHUJHFGT
    运行结果:HHNUHHUJHFGT
  13. 字符串第一个字符大写:str.capitalize()
    代码:
    str = "woshiasddscv"
    print str.capitalize()  #Woshiasddscv
    运行结果:Woshiasddscv
  14. 每个单词首字母大写:str.title()
    代码:
    str = "hah hsauh"
    print str.title()  #Hah Hsauh
    运行结果:Hah Hsauh
  15. 以xx结尾(文件后缀名判断):file.endswith(str)
    代码:
    file = "ancd.txt"
    print file.endswith(".txt") #True
    print file.endswith(".pdf") #False
    运行结果:

  16. 以xx开头:file.startswith(str)
    代码:
    file = "ancd.txt"
    print file.startswith("ancd")   #True
    print file.startswith("ancds")  #False
    运行结果:

猜你喜欢

转载自blog.csdn.net/carfge/article/details/79610584