更新一篇python字符串操作函数,未经允许切勿擅自转载。
- 字符串拼接:a+b
代码:
运行结果:a = "woshi" b = "carcar96" print a+b #方法1 print "==%s=="%(a+b) #方法2
- 获取字符串长度:len(str)
结果:
运行结果:12str = "woshiasddscv" print(len(str))
- 获取字符串的第几个:str[i]
代码:
运行结果:wstr = "woshiasddscv" print(str[0])
- 获取字符串的最后一个
代码:
运行结果:str = "woshiasddscv" print(str[-1]) print(str[len(str)-1])
- 字符串切片:获取字符串中的第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
- 字符串倒序
代码:
运行结果:str = "woshiasddscv" print str[-1::-1] #vcsddsaihsow print str[::-1] #vcsddsaihsow
- 查找字符串,返回查找到的第一个目标下标,找不到返回-1:str.find("s")
代码:
运行结果:str = "woshiasddscv" print str.find("s") #2 print str.find("gg") #-1
- 统计字符串中,某字符出现的次数:str.count("s")
代码:
运行结果:str = "woshiasddscv" print str.count("s") #3 print str.count("gg") #0
- 字符串替换: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
- 字符串分割:str.split("s")
代码:
运行结果:['wo', 'hia', 'dd', 'cv']str = "woshiasddscv" print str.split("s") #['wo', 'hia', 'dd', 'cv']
- 字符串全部变小写:str.lower()
代码:
运行结果:hhnuhhujhfgtstr = "HhnuhHUJHfgt" print str.lower() #hhnuhhujhfgt
- 字符串全部变大写:str.upper()
代码:
运行结果:HHNUHHUJHFGTstr = "HhnuhHUJHfgt" print str.upper() #HHNUHHUJHFGT
- 字符串第一个字符大写:str.capitalize()
代码:
运行结果:Woshiasddscvstr = "woshiasddscv" print str.capitalize() #Woshiasddscv
- 每个单词首字母大写:str.title()
代码:
运行结果:Hah Hsauhstr = "hah hsauh" print str.title() #Hah Hsauh
- 以xx结尾(文件后缀名判断):file.endswith(str)
代码:
运行结果:file = "ancd.txt" print file.endswith(".txt") #True print file.endswith(".pdf") #False
- 以xx开头:file.startswith(str)
代码:
运行结果:file = "ancd.txt" print file.startswith("ancd") #True print file.startswith("ancds") #False