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应用的教程
Apr 16 Python
python使用scrapy发送post请求的坑
Sep 04 Python
Python3中内置类型bytes和str用法及byte和string之间各种编码转换 问题
Sep 27 Python
django+echart绘制曲线图的方法示例
Nov 26 Python
python3实现二叉树的遍历与递归算法解析(小结)
Jul 03 Python
Python 生成一个从0到n个数字的列表4种方法小结
Nov 28 Python
Python3列表List入门知识附实例
Feb 09 Python
Python3加密解密库Crypto的RSA加解密和签名/验签实现方法实例
Feb 11 Python
Pytest框架之fixture的详细使用教程
Apr 07 Python
Pytorch数据拼接与拆分操作实现图解
Apr 30 Python
PyCharm2019 安装和配置教程详解附激活码
Jul 31 Python
Python使用内置函数setattr设置对象的属性值
Oct 16 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
深入了解php4(2)--重访过去
2006/10/09 PHP
php摘要生成函数(无乱码)
2012/02/04 PHP
PHP中防止直接访问或查看或下载config.php文件的方法
2012/07/07 PHP
修改php.ini不生效问题解决方法(上传大于8M的文件)
2013/06/14 PHP
php接口数据加密、解密、验证签名
2015/03/12 PHP
laravel通过创建自定义artisan make命令来新建类文件详解
2017/08/17 PHP
PHP消息队列实现及应用详解【队列处理订单系统和配送系统】
2019/05/20 PHP
基础的prototype.js常用函数及其用法
2007/03/10 Javascript
JavaScript获得选中文本内容的方法
2008/12/02 Javascript
javascript 强制刷新页面的实现代码
2009/12/13 Javascript
一个简单的Ext.XTemplate的实例代码
2012/03/18 Javascript
浏览器兼容console对象的简要解决方案分享
2013/10/24 Javascript
jQuery中事件对象e的事件冒泡用法示例介绍
2014/04/25 Javascript
HTML5+setCutomValidity()函数验证表单实例分享
2015/04/24 Javascript
jquery获取img的src值的简单实例
2016/05/17 Javascript
深入理解jquery中的事件与动画
2016/05/24 Javascript
Bootstrap源码解读按钮(5)
2016/12/23 Javascript
js如何获取网页所有图片
2017/05/12 Javascript
javascript计算对象长度的方法
2017/10/25 Javascript
layer弹出子iframe层父子页面传值的实现方法
2018/11/22 Javascript
关于AOP在JS中的实现与应用详解
2019/05/06 Javascript
操作按钮悬浮固定在微信小程序底部的实现代码
2019/08/02 Javascript
Websocket 向指定用户发消息的方法
2020/01/09 Javascript
js实现select下拉框选择
2020/01/11 Javascript
python解析xml文件操作实例
2014/10/05 Python
python 定时器,实现每天凌晨3点执行的方法
2019/02/20 Python
python占位符输入方式实例
2019/05/27 Python
Python图片处理模块PIL操作方法(pillow)
2020/04/07 Python
什么是python的列表推导式
2020/05/26 Python
通过cmd进入python的步骤
2020/06/16 Python
班子群众路线教育实践个人对照检查材料思想汇报
2014/09/30 职场文书
2014财务年终工作总结
2014/12/08 职场文书
4S店客服专员岗位职责
2015/04/07 职场文书
普希金诗歌赏析(6首)
2019/08/22 职场文书
vue使用echarts实现折线图
2022/03/21 Vue.js
java实现自定义时钟并实现走时功能
2022/06/21 Java/Android