在日常编程中,对字符串的操作往往是比较频繁的。Python给我们内置一些比较常用的方法。来方便我们日常的操作。下面我这边博客就将字符串的一些常用方法进行罗列出来。方便大家在使用的时候查询。
常用功能
startswith()判断字符串是否以XX开头,得到一个布尔值
v1 = "叨逼叨的一天,烦死了"
# True
result = v1.startswith("叨逼叨的一天")
print(result) # 值为True
endswith()判断字符串是否以XX结尾,等到一个布尔值
v1 = "叨逼叨的一天,烦死了"
result = v1.endswith("烦死了")
print(result) # 值为True
isdecimal()判断字符串是否是十进?得到一个布尔值
v1 = "1238871"
result = v1.isdecimal()
print(result) # True
isdigit()判断字符串是否是数字?得到一个布尔值
str = "123456"; # Only digit in this string
print str.isdigit();
str = "this is string example....wow!!!";
print str.isdigit();
strip()去除字符串两边的 空格、换行符、制表符,得到一个新字符串
lstrip()删除左侧
rstrip()删除右侧
data = input("请输入内容:") #武沛齐,武沛齐
print(data)
msg = " H e ll o啊,树哥 "
data = msg.strip()
print(data) # 将msg两边的空白去掉,得到"H e ll o啊,树哥"
msg = " H e ll o啊,树哥 "
data = msg.lstrip()
print(data) # 将msg左边的空白去掉,得到"H e ll o啊,树哥 "
msg = " H e ll o啊,树哥 "
data = msg.rstrip()
print(data) # 将msg右边的空白去掉,得到" H e ll o啊,树哥"
删除两边指定内容
msg = "哥H e ll o啊,树哥"
data = msg.strip("哥")
print(data) # 将msg两边的空白去掉,得到"H e ll o啊,树"
msg = "哥H e ll o啊,树哥"
data = msg.lstrip("哥")
print(data) # 将msg左边的空白去掉,得到"H e ll o啊,树哥"
msg = "哥H e ll o啊,树哥"
data = msg.rstrip("哥")
print(data) # 将msg右边的空白去掉,得到"哥H e ll o啊,树"
upper()字符串变大写,得到一个新字符串
msg = "my name is oliver queen"
data = msg.upper()
print(msg) # my name is oliver queen
print(data) # 输出为:MY NAME IS OLIVER QUEEN
capitalize() 字符串首字母变大写
>>>s = 'a, B'
>>> s.capitalize()
'A, b'
>>> s = ' a, B' # a 前面有空格
>>> s.capitalize()
' a, b'
>>> s = 'a, BCD'
>>> s.capitalize()
'A, bcd'
lower()字符串变小写,得到一个新字符串
msg = "My Name Is Oliver Queen"
data = msg.lower()
print(data) # 输出为:my name is oliver queen
replace()字符串内容替换,得到一个新的字符串
data = "你是个好人,但是好人不合适我"
value = data.replace("好人","贱人")
print(data) # "你是个好人,但是好人不合适我"
print(value) # "你是个贱人,但是贱人不合适我"
一个典型的屏蔽案例
char_list = ["吗","逗比","二蛋","钢球"] # 创建一个数组用于存放需要屏蔽的词语
content = input("请输入评论信息") # 输入句子
for item in char_list: # 循环char_list列表
content = content.repalce(item,"**") # 将词语屏蔽得到一个新的句子content
print(content)
split()字符串切割得到一个列表
data = "武沛齐|root|wupeiqi@qq.com"
result = data.split('|') # ["武沛齐","root","wupeiqi@qq.com"]
print(data) # "武沛齐|root|wupeiqi@qq.com"
print(result) # 输出 ["武沛齐","root","wupeiqi@qq.com"] 根据特定字符切开之后保存在列表中,方便以后的操作
可切割列表长度
data = "武沛齐|root|wupeiqi@qq.com"
v1 = data.split("|") # ['武沛齐', 'root', 'wupeiqi@qq.com']
print(v1)
v2 = data.split("|", 2) # ['武沛齐', 'root|wupeiqi@qq.com']
print(v2)
rsplit()切割位置
data = "武沛齐,root,wupeiqi@qq.com"
v1 = data.rsplit(',')
print(v1) # ['武沛齐', 'root', 'wupeiqi@qq.com']
v2 = data.rsplit(',',1)
print(v2) # ['武沛齐,root', 'wupeiqi@qq.com']
join()字符串拼接,得到一个新的字符串
data_list = ["alex","是","大烧饼"]
v1 = "_".join(data_list) # alex_是_大烧饼
print(v1)
count()统计字符串里某个字符或子字符串出现的次数
str = "this is string example....wow!!!";
sub = "i";
print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
sub = "wow";
print "str.count(sub) : ", str.count(sub)