python3字符串操作总结


Posted in Python onJuly 24, 2019

介绍Python常见的字符串处理方式

字符串截取

>>>s = 'hello'
>>>s[0:3]
'he' 
>>>s[:] #截取全部字符
'hello'

消除空格及特殊符号    

s.strip() #消除字符串s左右两边的空白字符(包括'\t','\n','\r','')
 
s.strip('0') #消除字符串s左右两边的特殊字符(如'0'),字符串中间的'0'不会删除

例如:

>>>s = '000hello00world000'
>>>s.strip('0')
'hello00world'
s.strip('12')等价于s.strip('21')

例如:

>>>s = '12hello21'
>>>s.strip('12')
'hello'

lstrip,rstrip 用法与strip类似,分别用于消除左、右的字符

字符串复制

s1 = 'hello'
s2 = s1 # s2 = 'hello'

若指定长度

s1 = 'hello'
s2 = s1[0:2] #s2 = 'he'

字符串连接

s1 = 'hello'
s2 = 'world'
s3 = s1 + s2 #s3 = 'helloworld'

或者

import operator
s3 = operator.concat(s1,s2) #concat为字符串拼接函数

字符串比较

(1)利用operator模块方法比较(python3.X取消了cmd函数)

包含的方法有:

  • lt(a, b) ———— 小于
  • le(a, b) ———— 小于等于
  • eq(a, b) ———— 等于
  • ne(a, b) ———— 不等于
  • ge(a, b) ———— 大于等于
  • gt(a, b) ———— 大于

例子:

>>>import operator
>>>operator.eq('abc','edf') #根据ASCII码比较
Flase
>>>operator.gt('abc','ab')
True

(2)关系运算符比较(>,<,>=,<=,==,!=)

>>>s1 = 'abc'
>>>s2 = 'ab'
>>>s1 > s2
True
>>>s1 == s2
False

求字符串长度

>>>s1 = 'hello'
>>>len(s1)
5

求字符串中最大字符,最小字符

>>>s1 = 'hello'
>>>max(s1) #求字符串s1中最大字符
'o'
>>>min(s1) #求字符串s2中最小字符
'e'

字符串大小写转换

主要有如下方法:

  1. upper ———— 转换为大写
  2. lower ———— 转换为小写
  3. title ———— 转换为标题(每个单词首字母大写)
  4. capitalize ———— 首字母大写
  5. swapcase ———— 大写变小写,小写变大写

例子:

>>>s1 = 'hello'
>>>s2 = 'WORLD'
>>>s3 = 'hello world'
>>>s1.upper() 
'HELLO'
>>>s2.lower() 
'world'
>>>s3.title() 
'Hello World'
>>>s3.capitalize() 
'Hello world'
>>>s3.title().swapcase() 
'hELLO wORLD'

字符串翻转

>>>s1 = 'hello'
>>>s1[::-1]
'olleh'

字符串分割

split方法,根据参数进行分割,返回一个列表

例子:

>>>s1 = 'hello,world'
>>>s1.split(',')
['hello','world']

字符串序列连接

join方法:

语法为str.join(seq) #seq为元素序列

例子:

>>>l = ['hello','world']
>>>str = '-'
>>>str.join(l)
'hello-world'

字符串内查找

find方法:

检测字符串内是否包含子串str

语法为:

str.find(str[,start,end]) #str为要查找的字符串;strat为查找起始位置,默认为0;end为查找终止位置,默认为字符串长度。若找到返回起始位置索引,否则返回-1

例子:

>>>s1 = 'today is a fine day'
>>>s1.find('is')
6
>>>s1.find('is',3)
6
>>>s1.find('is',7,10)
-1

字符串内替换

replace方法:

把字符串中的旧串替换成新串

语法为:

str.replace(old,new[,max]) #old为旧串,new为新串,max可选,为替换次数

例子:

>>>s1 = 'today is a find day'
>>>s1.replace('find','rainy')
'today is a rainy day'

判断字符串组成

主要有如下方法:

  • isdigit ———— 检测字符串时候只由数字组成
  • isalnum ———— 检测字符串是否只由数字和字母组成
  • isalpha ———— 检测字符串是否只由字母组成
  • islower ———— 检测字符串是否只含有小写字母
  • isupper ———— 检测字符串是否只含有大写字母
  • isspace ———— 检测字符串是否只含有空格
  • istitle ———— 检测字符串是否是标题(每个单词首字母大写)

例子:

>>>s1 = 'hello'
>>>s1.islower()
True
>>>s1.isdigit()
False

字符串转数组

a = 'My name is Jason'
#使用split(str="", num=string.count(str)) 方法根据不同的分割符转,也可指定分割次数,可使用 ' '.join方法转回
>>> 'My name is Jason'.split(' ')
['My', 'name', 'is', 'Jason']
>>> ' '.join(['My', 'name', 'is', 'Jason'])
'My name is Jason'

字符串首尾匹配

>>> 'cat.jpg'.startswith('cat')
True
>>> 'cat.jpg'.startswith('cat',0,3)
True
>>> 'cat.jpg'.endswith('.jpg')
True
>>> 'cat.jpg'.endswith('.jpg',-4)
True

字符串空格处理

>>> s = ' Hello World  '
>>> s.strip()
'Hello World'
>>> s.lstrip()
'Hello World  '
>>> s.rstrip()
' Hello World'
#扩展
>>> 'www.example.com'.lstrip('www.')
'example.com'
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'

字符串格式化、数字及大小写判断、长度补全

#字符串的格式化
>>> '{name},{sex},{age}'.format(age=15,sex='male',name='小安')
'小安,male,15'
>>> '{1},{0},{2}'.format('15','小安','male')
'小安,15,male'
>>> '{},{},{}'.format('小安', '15','male')
'小安,15,male'

#如果字符串中的所有字符都是数字,并且至少有一个字符,则返回真,否则返回假
>>> '123'.isdigit()
True
>>> '123一二三'.isdigit()
False
#isnumeric 是所有字符都是数字字符返回真
>>> '123一二三'.isnumeric()
True

#字符串是否大小写判断
>>> 'abc'.islower()
True
>>> 'Abc'.islower()
False
>>> 'ABC'.isupper()
True

#首字母大写
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
#正则处理方式
>>> import re
>>> def titlecase(s):
...   return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
...          lambda mo: mo.group(0)[0].upper() +
...               mo.group(0)[1:].lower(),
...          s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."

#返回指定长度字符串,前面补0,一般存csv文件中含00开头的字符0会被抹掉
>>> code = '1'
>>> code.zfill(6)
'000001'

#字符串长度及遍历
>>> s = '混蛋哥'
>>> len(s)
3
>>> for i in s:
  print(i)
混
蛋
哥
>>>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
零基础写python爬虫之抓取百度贴吧并存储到本地txt文件改进版
Nov 06 Python
Python使用scrapy抓取网站sitemap信息的方法
Apr 08 Python
Python计算三维矢量幅度的方法
Jun 15 Python
python计算一个序列的平均值的方法
Jul 11 Python
解析Python中的生成器及其与迭代器的差异
Jun 20 Python
Python脚本实时处理log文件的方法
Nov 21 Python
详解使用python的logging模块在stdout输出的两种方法
May 17 Python
python 表达式和语句及for、while循环练习实例
Jul 07 Python
python3 破解 geetest(极验)的滑块验证码功能
Feb 24 Python
对Xpath 获取子标签下所有文本的方法详解
Jan 02 Python
解决pycharm中导入自己写的.py函数出错问题
Feb 12 Python
Python生成九宫格图片的示例代码
Apr 14 Python
django数据关系一对多、多对多模型、自关联的建立
Jul 24 #Python
django如何自己创建一个中间件
Jul 24 #Python
django如何通过类视图使用装饰器
Jul 24 #Python
django 类视图的使用方法详解
Jul 24 #Python
django如何实现视图重定向
Jul 24 #Python
python字符串分割及字符串的一些常规方法
Jul 24 #Python
django使用haystack调用Elasticsearch实现索引搜索
Jul 24 #Python
You might like
php下判断数组中是否存在相同的值array_unique
2008/03/25 PHP
CI框架装载器Loader.php源码分析
2014/11/04 PHP
php实现Session存储到Redis
2015/11/11 PHP
javascript 密码框防止用户粘贴和复制的实现代码
2014/02/17 Javascript
js实现网站最上边可关闭的浮动广告条代码
2015/09/04 Javascript
jQuery+PHP+MySQL二级联动下拉菜单实例讲解
2015/10/27 Javascript
js中substring和substr两者区别和使用方法
2015/11/09 Javascript
jQuery插件之Tocify动态节点目录菜单生成器附源码下载
2016/01/08 Javascript
jQuery Easyui datagrid editor为combobox时指定数据源实例
2016/12/19 Javascript
Vue 过渡(动画)transition组件案例详解
2017/01/22 Javascript
ionic环境配置及问题详解
2017/06/27 Javascript
Angular angular-file-upload文件上传的示例代码
2018/08/23 Javascript
解决vue中修改了数据但视图无法更新的情况
2018/08/27 Javascript
thinkjs微信中控之微信鉴权登陆的实现代码
2019/08/08 Javascript
Angular8路由守卫原理和使用方法
2019/08/29 Javascript
nodeJs项目在阿里云的简单部署
2020/11/27 NodeJs
[01:15:56]2018DOTA2亚洲邀请赛3月30日 小组赛A组 TNC VS Newbee
2018/03/31 DOTA
Python导出DBF文件到Excel的方法
2015/07/25 Python
Python中常用操作字符串的函数与方法总结
2016/02/04 Python
Python中asyncio模块的深入讲解
2019/06/10 Python
django 微信网页授权登陆的实现
2019/07/30 Python
Python+OpenCV 实现图片无损旋转90°且无黑边
2019/12/12 Python
TFRecord文件查看包含的所有Features代码
2020/02/17 Python
python如何获得list或numpy数组中最大元素对应的索引
2020/11/16 Python
Python如何使用神经网络进行简单文本分类
2021/02/25 Python
python 求两个向量的顺时针夹角操作
2021/03/04 Python
北大研究生linux应用求职信
2013/10/29 职场文书
初中三年毕业生的自我评价分享
2014/02/14 职场文书
大学运动会入场词
2014/02/22 职场文书
《邮票齿孔的故事》教学反思
2014/02/22 职场文书
公司证明怎么写
2014/09/22 职场文书
帝企鹅日记观后感
2015/06/10 职场文书
接收函
2019/04/22 职场文书
MySQL 存储过程的优缺点分析
2021/05/20 MySQL
手把手教你用SpringBoot将文件打包成zip存放或导出
2021/06/11 Java/Android
关于React Native使用axios进行网络请求的方法
2021/08/02 Javascript