字符串相关函数

1.首字母大小写

capitalize()#首字母大写

title()#返回"标题化"的字符串,就是说所有单词的首个字母转化为大写

world="hello_world_welcome_to_shenzhen"
print(world.capitalize())
print(world.title())

 

 

2.upper()方法将字符串中的小写字母转换为大写字母

lower() 将字符串中的所有大写字母装换为小写
world="hello_world_welcome_to_shenzhen"=
print(world.upper())


string_2_1='TODAY IS SUNNY DAY ,I GOING FISHING'
print (string_2_1.lower())

 

 

 3.count()统计字符串里某个字符出现的次数

world="hello_world_welcome_to_shenzhen"
print(world.count("n"))

 
world="hello_world_welcome_to_shenzhen"
print(world.count("e",0,2))#统计范围的开始和结束

 

 

4.join()把用于将序列中的元素以指定的字符连接生成一个新的字符串。

name = "hello_wuchuan"
dian = "."
print(dian.join(name))

tup_2
= ('34', '3', '5', 'e') sl = "_" print(sl.join(tup_2))

 

 

 

5.split()把字符串通过指定标识符分割为序列

name = "he_l_lo_wu_chuan"
print(name.split("_"))

name = 't-J-a-y'
new_name = name.split('-')
print(new_name)

result = ''.join(new_name)
print(result)

 

6.strip()用于移除字符串头尾指定的字符(默认为空格)

str_1='ab34kdfgnergndvnvabdflgkdnabaabababldgjdnljbabbbbbbbbbbbbb'
new_str_1=str_1.strip("ab")
print(new_str_1)

 

7.startswith()函数判断文本是否以某个字符开始

name = ['张三','李四','王五','赵六','张强','李白','李杜']
count1 = 0
count2 = 0
count3 = 0
for i in name:
    if i.startswith(''):
        count1 += 1
    elif i.startswith(''):
        count2 += 1
    elif i.startswith(''):
        count3 += 1
print ('全班姓张的有%d 人,全班姓李的有%d 人,全班姓王的有%d 人'%(count1,count2,count3))

 

 

8.index()检测字符串中是否包含子字符串 str(返回的是该字符串的索引值)

str_1='shenzhenwuchuan'
 #找到了,返回字符串的开始索引号
new_str_1=str_1.index("wu")
print(new_str_1)

 
#未找到时报错:ValueError: substring not found
new_str_1=str_1.index("na")
print(new_str_1)

 

9.replace()字符串替换

replace(old_str,new_old)

str_1="我爱python"
print(str_1.replace("python","China"))
str_1="shenzhenwuchuan"
print(str_1.replace("shenzhen",""))

 

10.find()从左边开始查询字符串

(1)find("str",start,end) 

  • "str":待查的字符
  • start:表示开始查询的索引值
  • end:表示查询结束的索引值

(2)当查询到结果后,返回字符串的索引值

str_1="shenzhenwuchuan"
print(str_1.find("shen",0,-1))

(3)当查询不到时,返回的结果为-1

str_1="shenzhenwuya"
print(str_1.find("sss",0,-1))

 

 

 

 

posted @ 2020-04-02 16:37  测试-dali  阅读(163)  评论(0编辑  收藏  举报