您的位置:首页 > 编程语言 > Python开发

python2之字符串操作

2018-03-19 14:26 183 查看

    更新一篇python字符串操作函数,未经允许切勿擅自转载。
字符串拼接:a+b
代码:
a = "woshi"
b = "carcar96"

print a+b                #方法1
print "==%s=="%(a+b)     #方法2
运行结果:



获取字符串长度:len(str)
结果:
str = "woshiasddscv"
print(len(str))
运行结果:12

获取字符串的第几个:str[i]
代码:
str = "woshiasddscv"
print(str[0])
运行结果:w

获取字符串的最后一个
代码:
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")
代码:
str = "woshiasddscv"
print str.split("s")    #['wo', 'hia', 'dd', 'cv']
运行结果:['wo', 'hia', 'dd', 'cv']

字符串全部变小写:str.lower()
代码:
str = "HhnuhHUJHfgt"
print str.lower()  #hhnuhhujhfgt
运行结果:hhnuhhujhfgt

字符串全部变大写:str.upper()
代码:
str = "HhnuhHUJHfgt"
print str.upper()  #HHNUHHUJHFGT
运行结果:HHNUHHUJHFGT

字符串第一个字符大写:str.capitalize()
代码:
str = "woshiasddscv"
print str.capitalize()  #Woshiasddscv
运行结果:Woshiasddscv

每个单词首字母大写:str.title()
代码:
str = "hah hsauh"
print str.title()  #Hah Hsauh
运行结果: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
运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python python2 字符串