码迷,mamicode.com
首页 > 编程语言 > 详细

[Python Study Notes]字符串操作

时间:2018-01-09 16:58:49      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:not   包含   字母   max   nbsp   style   串操作   gpo   round   

                     

 字符串操作    

                                                                   

 

a.字符串格式化输出

1 name = "liu"
2 print "i am %s " % name
3    
4 #输出: i am liu  
6 PS: 字符串是 %s;整数 %d;浮点数%f

 b.查找字符串(find)

1 str.find(str, start=0, end=len(mystr))   # 检测 str 是否包含在 mystr中,如果是返回开始的索引值,否则返回-1

 

1 >>> str = xinge 好帅
2  
3 >>> str.find(xing)
4 0
5  
6 >>> str.find()
7 6

 c.查找替换字符串中内容(replace)

1 mystr.replace(str1, str2, mystr.count(str1))  # 把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.

 

1 >>> str = abcabcabc
2  
3 >>> str.replace(a,xinge,2)
4 xingebcxingebcabc

 d.以str为分割符切片(split)

mystr.split(str=" ", 2) # 以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串

 

1 >>> str = a\nb\tc
2  
3 >>> str
4 a\nb\tc
5  
6 >>> str.split()
7 [a, b, c]

 f.将字符串首字母大写(capitalize)

1 >>> str=abc
2  
3 >>> str.capitalize()
4 Abc

g.把字符串的每个单词首字母大写(title)

1 >>> str = "hello world"
2  
3 >>> str.title()
4 Hello World

 h.startswith,endswith

1 startswith  # 检查字符串是否是以str 开头, 是则返回 True,否则返回 False
2 endswith  # 检查字符串是否以str结束,如果是返回True,否则返回 False.

 i.upper,lower

1 upper  # 转换 mystr 中所有字符为大写
2 lower  # 转换 mystr 中所有字符为小写

 j.strip,lstrip,rstrip

1 strip  # 清除左右两边的空格
2 lstrip  # 清除左边的空格
3 rstrip  # 清除右边的空格

k.join

1 mystr.join(str)  # mystr 中每个字符后面插入str,构造出一个新的字符串

 

                                                                           欢迎补充!                                                                

 

[Python Study Notes]字符串操作

标签:not   包含   字母   max   nbsp   style   串操作   gpo   round   

原文地址:https://www.cnblogs.com/liu66blog/p/8157878.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!