Python基础之字符串常见操作经典实例详解


Posted in Python onFebruary 26, 2020

本文实例讲述了Python基础之字符串常见操作。分享给大家供大家参考,具体如下:

字符串基本操作

切片
# str[beg:end]
# (下标从 0 开始)从下标为beg开始算起,切取到下标为 end-1 的元素,切取的区间为 [beg, end)
str = ' python str '
print (str[3:6])  # tho
# str[beg:end:step]
# 取 [beg, end) 之间的元素,每隔 step 个取一个
print (str[2:7:2]) # yhn
原始字符串
# 在字符串前加 r/R
# 所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符
print (r'\n')  # \n
字符串重复
# str * n, n * str
# n 为一个 int 数字
str = "hi"
print (str*2)  # hihi
print (2*str)  # hihi
in
str = ' python'
print ('p' in str)  # True
print ('py' in str)  # True
print ('py' not in str) # False

字符串常用函数

去空格
str = ' python str '
print (str)
# 去首尾空格
print (str.strip())
# 去左侧空格
print (str.lstrip())
# 去右侧空格
print (str.rstrip())
分隔字符串
str = ' 1 , 2 , 3 , 4 , 5 , '
# 默认使用空格分隔
print (str.split())  # ['1', ',', '2', ',', '3', ',', '4', ',', '5', ',']
# 指定使用空格进行分隔,首尾如果有空格,则会出现在结果中
print (str.split(' ')) # ['', '1', ',', '2', ',', '3', ',', '4', ',', '5', ',', '']
# 指定其他字符串进行分隔
print (str.split(',')) # [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' ']
print (str.split('3 ,')) # [' 1 , 2 , ', ' 4 , 5 , ']
str = 'mississippi'
print (str.rstrip('ip'))
# 取行, python 中把 "\r","\n","\r\n",作为行分隔符
str = 'ab c\n\nde fg\rkl\r\n'
print (str.splitlines())   # ['ab c', '', 'de fg', 'kl']
print (str.splitlines(True)) # ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
拼接字符串
# str.join()方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
str = '-'
seq = ("a", "b", "c"); # 字符串序列
print (str.join(seq)) # 'a-b-c'
统计字符串里某个字符出现的次数
str = "thing example....wow!!!"
print (str.count('i', 0, 5)) # 1
print (str.count('e') ) # 2
检测字符串中是否包含子字符串
# str.find(str, beg=0, end=len(string))
# 如果包含子字符串返回开始的索引值,否则返回-1。
str1 = "this is string example....wow!!!"
str2 = "exam"
print (str1.find(str2))   # 15
print (str1.find(str2, 10)) # 15
print (str1.find(str2, 40)) # -1

# str.index(str, beg=0, end=len(string))
# 如果包含子字符串返回开始的索引值,否则抛出异常。
print (str1.index(str2))   # 15
print (str1.index(str2, 10)) # 15
print (str1.index(str2, 40))
# Traceback (most recent call last):
#  File "test.py", line 8, in
#  print str1.index(str2, 40)
#  ValueError: substring not found
# shell returned 1

# str.rfind(str, beg=0, end=len(string))
# str.rindex(str, beg=0, end=len(string))
判断字符串是否以指定前缀、后缀结尾
# str.startswith(str, beg=0,end=len(string))
# 检查字符串以指定子字符串开头,如果是则返回 True,否则返回 False
str = "this is string example....wow!!!"
print (str.startswith( 'this' ))    # True
print (str.startswith( 'is', 2, 4 ))  # True
print (str.startswith( 'this', 2, 4 )) # False

# str.endswith(suffix[, start[, end]])
# 以指定后缀结尾返回True,否则返回False
suffix = "wow!!!"
print (str.endswith(suffix))    # True
print (str.endswith(suffix,20))   # True
suffix = "is"
print (str.endswith(suffix, 2, 4))  # True
print (str.endswith(suffix, 2, 6)) # False
根据指定的分隔符将字符串进行分割
# str.partition(del)
# 返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。
str = "http://www.baidu.com/"
print (str.partition("://"))  # ('http', '://', 'www.baidu.com/')
# string.rpartition(str)  从右边开始
替换字符串
# str.replace(old, new[, max])
# 字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
str = "thing example....wow!!! thisslly string";
print (str.replace("is", "was"))   # thwas was string example....wow!!! thwas was really string
print (str.replace("is", "was", 3)) # thwas was string example....wow!!! thwas is really string
# str.expandtabs(tabsize=8)
# 把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8
检测字符串组成
# 检测数字
str.isdigit()  # 检测字符串是否只由数字组成
str.isnumeric() # 检测字符串是否只由数字组成,这种方法是只针对unicode对象
str.isdecimal() # 检查字符串是否只包含十进制字符。这种方法只存在于unicode对象
# 检测字母
str.isalpha()  # 检测字符串是否只由字母组成
# 检测字母和数字
str.isalnum()  # 检测字符串是否由字母和数字组成
# 检测其他
str.isspace()  # 检测字符串是否只由空格组成
str.islower()  # 检测字符串是否由小写字母组成
str.isupper()  # 检测字符串中所有的字母是否都为大写
str.istitle()  # 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写
字符串处理
str.capitalize()  # 将字符串的第一个字母变成大写,其他字母变小写
str.lower()    # 转换字符串中所有大写字符为小写
str.upper()    # 将字符串中的小写字母转为大写字母
str.swapcase()   # 对字符串的大小写字母进行转换
max(str)  # 返回字符串 str 中最大的字母
min(str)  # 返回字符串 str 中最小的字母
len(str)  # 返回字符串的长度
str(arg) # 将 arg 转换为 string

格式化输出

居中填充
# str.center(width[, fillchar])
# 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格
str = "this is string example....wow!!!"
print (str.center(40, 'a'))  # aaaathis is string example....wow!!!aaaa
靠右填充
# str.zfill(width)
# 返回指定长度的字符串,原字符串右对齐,前面填充0
str = "this is string example....wow!!!"
print (str.zfill(40))  # 00000000this is string example....wow!!!
输出格式
print ("My name is %s and weight is %d kg!" % ('Cool', 21))
# My name is Zara and weight is 21 kg!
print ('%(language)s has %(number)03d quote types.' % {"language": "Python", "number": 2})
# Python has 002 quote types.
# str.format(*args, **kwargs)
print ('{0}, {1}, {2}'.format('a', 'b', 'c')) # a, b, c
print ('{1}, {0}, {2}'.format('a', 'b', 'c')) # b, a, c

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python实现简单socket程序在两台电脑之间传输消息的方法
Mar 13 Python
Python基于smtplib实现异步发送邮件服务
May 28 Python
用python实现对比两张图片的不同
Feb 05 Python
python3 图片referer防盗链的实现方法
Mar 12 Python
python实现指定文件夹下的指定文件移动到指定位置
Sep 17 Python
python调用自定义函数的实例操作
Jun 26 Python
Python寻找路径和查找文件路径的示例
Jul 10 Python
python 哈希表实现简单python字典代码实例
Sep 27 Python
Python流程控制常用工具详解
Feb 24 Python
基于Python脚本实现邮件报警功能
May 20 Python
教你如何使用Python实现二叉树结构及三种遍历
Jun 18 Python
利用Python实时获取steam特惠游戏数据
Jun 25 Python
浅析python表达式4+0.5值的数据类型
Feb 26 #Python
Pandas时间序列基础详解(转换,索引,切片)
Feb 26 #Python
Python图像处理库PIL的ImageFont模块使用介绍
Feb 26 #Python
Python利用FFT进行简单滤波的实现
Feb 26 #Python
Python图像处理库PIL的ImageGrab模块介绍详解
Feb 26 #Python
Python图像处理库PIL的ImageDraw模块介绍详解
Feb 26 #Python
PIL包中Image模块的convert()函数的具体使用
Feb 26 #Python
You might like
菜鸟学PHP之Smarty入门
2007/01/04 PHP
php access 数据连接与读取保存编辑数据的实现代码
2010/05/12 PHP
解析mysql中UNIX_TIMESTAMP()函数与php中time()函数的区别
2013/06/24 PHP
9个经典的PHP代码片段分享
2014/12/18 PHP
PHP下使用mysqli的函数连接mysql出现warning: mysqli::real_connect(): (hy000/1040): ...
2016/02/14 PHP
php file_get_contents取文件中数组元素的方法
2017/04/01 PHP
JavaScript中的Screen屏幕对象
2008/01/16 Javascript
JQuery jsonp 使用示例代码
2009/08/12 Javascript
js内置对象 学习笔记
2011/08/01 Javascript
javascript学习笔记(二) js一些基本概念
2012/06/18 Javascript
JQuery触发radio或checkbox的change事件
2012/12/18 Javascript
Javascript实现关联数据(Linked Data)查询及注意细节
2013/02/22 Javascript
20行代码实现的一个CSS覆盖率测试脚本
2013/07/07 Javascript
通过js获取div的background-image属性
2013/10/15 Javascript
jquery 插件实现瀑布流图片展示实例
2015/04/03 Javascript
js实现YouKu的漂亮搜索框效果
2015/08/19 Javascript
jQuery实现的导航动画效果(附demo源码)
2016/04/01 Javascript
浅谈js数据类型判断与数组判断
2016/08/29 Javascript
微信小程序 加载 app-service.js 错误解决方法
2016/10/12 Javascript
ztree实现左边动态生成树右边为内容详情功能
2017/11/03 Javascript
详解vue更改头像功能实现
2019/04/28 Javascript
使用Phantomjs和Node完成网页的截屏快照的方法
2019/07/16 Javascript
基于javascript实现日历功能原理及代码实例
2020/05/07 Javascript
解决vue net :ERR_CONNECTION_REFUSED报错问题
2020/08/13 Javascript
JS性能优化实现方法及优点进行
2020/08/30 Javascript
windows7 32、64位下python爬虫框架scrapy环境的搭建方法
2018/11/29 Python
Mac中PyCharm配置Anaconda环境的方法
2020/03/04 Python
python selenium操作cookie的实现
2020/03/18 Python
HTML5使用drawImage()方法绘制图像
2014/06/23 HTML / CSS
如何用H5实现一个触屏版的轮播器的实例
2017/01/09 HTML / CSS
法学研究生自我鉴定范文
2013/12/04 职场文书
致200米运动员广播稿
2014/02/06 职场文书
创业者迈进成功第一步:如何写创业计划书?
2014/03/22 职场文书
道歉的话怎么说
2015/05/12 职场文书
Windows Server 2019 域控制器安装图文教程
2022/04/28 Servers
VUE解决跨域问题Access to XMLHttpRequest at
2022/05/06 Vue.js