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

关于python中字符串的操作方法

时间:2018-07-06 23:24:50      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:大小写   als   字符串大小   高薪   color   orm   class   大写   功能   

1.capitalize() 首字母大写

1 s = helloPython
2 s1 = s.capitalize()  #首字母大写
3 print(s1)         #输出结果:Hellopython

2.upper()  全部大写,lower() 全部小写

1 s = helloPython
2 s2 = s.upper()    #全部大写
3 s21 = s.lower()     #全部小写
4 print(s1,s21)    #输出结果:Hellopython hellopython

3.swapcas()  字符串大小写反转

1 s = helloPython
2 s3 = s.swapcase()    #大小写反转
3 print(s3)             #输出结果:HELLOpYTHON

4.title()  每个被特殊字符或者数字隔开的子字符串首字母大写

1 #每个隔开的首字母大写
2 n = alex egon wusir  #以空格或者特殊字符(包括数字)来分割
3 s4 = n.title()
4 print(s4)            #输出结果:Alex Egon Wusir

5.cente()  居中,空白填充

1 s = alexWUsir
2 s5 = s.center(20)
3 s6 = s.center(20,#)
4 print(s5)  #输出结果:     alexWUsir
5 print(s6)  #输出结果:#####alexWUsir######

6.len()  公共方法

1 s = helloPython
2 l = len(s)
3 print(l)      #输出结果:11

7.startswith()  判断元素以什么开头

1 #以什么开头:startswith
2 s = helloPython
3 s7 = s.startswith(he)   #是不是以he开头
4 s71 = s.startswith(e, 2, 5)  #在切片范围内是否为e开头
5 print(s7,s71)              #输出结果:True False

8.find()  通过元素找索引,找不到则返回-1

1 #find 找索引
2 s = helloPython
3 s8 = s.find(P)     #通过元素找索引,找不到返回-1
4 print(s8,type(s8))   #输出结果:5 <class ‘int‘>

9.index()  同find()功能几乎一样,但是找不到会报错

1 #index
2 s = helloPython
3 s9 = s.index(P)     #同find功能几乎一样,但是找不到会报错
4 print(s9)            #输出结果:5

 

10.strip()  默认删除前后空格,也可以特定删除

1 s =      helloPython     
2 s9 = s.strip()
3 print(s9)       #输出结果:helloPython
4 s = %$hellopython%$
5 s91 = s.strip(%$) #包含的全部删除
6 #应用
7 #username = input(‘请输入您的用户名:‘).strip() #防止用户输入时前后有出现空格
8 #if username == ‘春哥‘:
9 #    print(‘恭喜春哥发财‘)

10 #补充:
还有rstrip,lstrip只删除单边

11.count()  计算出某一元素或字符串在另一个字符串中出现的次数

1 s = aishdijuviujsdnfiu
2 s10 = s.count(s)
3 print(s10)  #输出结果:2

12.split()  以某元素为标志分割,也是字符串转变为列表的方法

1 s = ;ais;fads;fasd;qer;
2 l = s.split(;)
3 print(l)

13.format 的三种玩法 格式化输出

1 #format的三种玩法  格式化输出
2 s = 我叫{},今年{},爱好{}.format(python,36,girl)  #{}相当于%s占位
3 print(s)   #输出结果:我叫python,今年36,爱好girl
4 s = 我叫{0},今年{1},爱好{0}.format(python,36)  #{}相当于%s占位
5 print(s)     #输出结果:我叫python,今年36,爱好python
6 s = 我叫{name},今年{age},爱好{hobby}.format(name = python,age = 36, hobby = girl)  #要以键值对形式写
7 print(s)    #输出结果:我叫python,今年36,爱好girl

14.replace()  查找并替换需要替换的元素,默认替换所有

1 s = 我们一定要学好python,学好了python我们可以拿高薪
2 print(s)
3 s11 = s.replace(学好,精通)
4 print(s11)  #输出结果:我们一定要学好python,学好了python我们可以拿高薪 
#我们一定要精通python,精通了python我们可以拿高薪

15.in  判断一个元素在不在一个字符串内

1 s = asiudhf小泽玛利亚iauhdf
2 if 小泽玛利亚 in s:
3     print(您的评论有敏感词)   #输出结果:您的评论有敏感词

 16.is  三剑客

1 name=jinxin123
2 print(name.isalnum()) #字符串由字母或数字组成
3 print(name.isalpha()) #字符串只由字母组成
4 print(name.isdigit()) #字符串只由数字组成

 

关于python中字符串的操作方法

标签:大小写   als   字符串大小   高薪   color   orm   class   大写   功能   

原文地址:https://www.cnblogs.com/rcat/p/9275711.html

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