python的字符串操作
来源:互联网 发布:淘宝时间护照的表真吗 编辑:程序博客网 时间:2024/06/05 11:57
字符串最基础的操作:
拼接
总共三种方法:
- 1、最简单的,加号连接
string = 'hello '+'world! '
不过据说这种方法效率低……
不过我感觉做大的缺点是不能和运算相连接
- 2、用join链接
strList = ['hello ', 'world! '] str = ''.join(strList)
- 3、最好的方法,占位符替换
str = '%s%s' % ('hello' , 'world! ')
这是一种格式化的方法,功能最强大,最规整。推荐使用。而且数字是可以直接参与替换的,e.g:
str = r"hello world%s! " % (1)print str
结果是
hello world1!
截取
- 1、通过位置序号截取。
大家都知道python有两种序号方式,一个是从左往右序号从0开始,依次加1;
另一种是从右往左从-1开始,依次减1。
正序:
str = r"hello world%s! " % (1)print str[0:5]
结果:
hello
倒序:
str = r"hello world%s! " % (1)print str[-8:-1]
结果:
world1!
- 2、通过特殊符号截取
两步走,第一步找到特殊符号的位置(方法参照查找),第二部使用上述方法截取。
查找
查找到某个字符的位置
- 1、find函数
str = r"hello world! "a = str.find(' ')#查找单个字符print ab = str.find('ld')#查找字符串print b
结果:
59
- 2、index函数
str = r"hello world! "a = str.index('ld')print a
结果:
9
index区别于find的一点是,如果没有查到,会返回-1
分割
用某个特殊字符分割字符串,得到一个list
str = r"hello world! "a = str.split(' ')print a
结果:
['hello', 'world!', '']
大小写转换
大写:upper()函数
小写:lower()函数
首拼大写:capitalize()函数
是否大写:isupper() 函数
是否小写: islower()函数
是否首拼大写:istitle()函数
str = r"hello world! "a = str.upper()print a
结果:
HELLO WORLD!
阅读全文
2 0
- Python的字符串操作
- Python 字符串的操作
- python字符串的操作
- Python字符串的操作
- python的字符串操作
- Python的字符串操作
- python的字符串操作
- Python 对字符串的操作
- Python的字符串操作string
- python字符串的格式化操作
- Python中字符串的操作
- python字符串的特定操作
- python的字符串操作汇总
- 对Python字符串的操作
- Python实用的字符串操作
- Python中字符串的操作
- Python字符串的基本操作
- python中字符串的操作
- Shell-基础使用
- c# 如何弹出对话框
- 读 read
- Java中vector的使用详解
- CentOS 安装Httpie
- python的字符串操作
- 渐变效果
- oracle 远程访问数据库 ORA-01034和ORA-27101问题的一种解决方法
- 二叉树的最大深度
- Leetcode Java-Combination Sum
- 巧用kendo.format和kendo.toString 格式化0为空格(不显示)
- struts2值栈
- 8-32 判断一棵二叉树是否是完全二叉树
- typeof()和instanceof()用法