python3 字符串方法

python3 字符串方法

1.capitalize() 将字符串的第一个字符改为大写

1 >>> s='i love cnblog'
2 >>> s.capitalize()
3 'I love cnblog'

2.casefold() 将字符串所有字符改为小写

1 >>> (s.capitalize()).casefold()
2 'i love cnblog'

3.center(width) 将字符串居中,并用空格将字符串填充至width长度,空格均匀分布在两侧,当width<len(s)时没有效果

1 >>> s.center(20)
2 '   i love cnblog    '

4.count(sub[,start[,end]]) 返回sub在字符串里出现的次数,start,end为可选参数,决定范围

1 >>> s.count('0',5,13)
2 0
3 >>> s.count('o',5,13)
4 1
5 >>> s.count('o',0,13)
6 2

5.encode(encoding='utf-8',errors='strict') 以encoding指定的编码格式对字符串进行编码

1 >>> s.encode(encoding='utf-8',errors='strict')
2 b'i love cnblog'
1 >>> s.encode()
2 b'i love cnblog'

6.endswith(sub[,start[,end]]) 检查字符串是否以sub结尾,是返回True,否返回False,start,end为可选参数,决定范围

1 >>> s.endswith('!',0,13)
2 False
3 >>> s.endswith('g')
4 True

7.expandtabs([tabsize=8]) 把字符串的tab字符(\t)转化为空格,如不指定tabsize,默认为8个空格

1 >>> s.expandtabs()
2 'i love cnblog'
3 >>> s='\t i love cnblog\t'
4 >>> s.expandtabs()
5 '         i love cnblog  '

这里第一个\t转化为8个空格,第二个tab是在后面加了3个空格,与'cnblog'相加共8个字符,并不是直接加8个空格

8.find(sub[,start[,end]]) 检测sub是否在字符串中,如果在则返回index,否则返回-1,start,end为可选参数,决定范围

1 >>> s='i love cnblog'
2 >>> s.find('o')
3 3
4 >>> s.find('o',3,13)
5 3
6 >>> s.find('o',4,13)
7 11
8 >>> s.find('g',0,13)
9 12

这里返回的是sub的index,同时start,end都是包含的。

 9.index(sub[,start[,end]]) 类似find(),不同在于如果sub不在字符串中,返回的不是-1而是异常

1 >>> s='i love cnblog'
2 >>> s.index('o')
3 3
4 >>> s.index('h')
5 Traceback (most recent call last):
6   File "<pyshell#2>", line 1, in <module>
7     s.index('h')
8 ValueError: substring not found

10.isalnum() 如果字符串至少有一个字符,并且所有字符都是字母或数字则返回True,否则False

 1 >>> s='i love cnblog'#有空格
 2 >>> s.isalnum()
 3 False
 4 >>> s='ilovecnblog'
 5 >>> s.isalnum()
 6 True
 7 >>> s='11ii'
 8 >>> s.isalnum()
 9 True

11.isalpha() 如果字符串至少有一个字符,并且所有字符都是字母则返回True,否则False

1 >>> s='ilovecnblog'
2 >>> s.isalpha()
3 True

12.isdigit() 如果字符串只包含数字则返回True,否则返回False

1 >>> s='1234'
2 >>> s.isdigit()
3 True

13.isdecimal() 如果字符串只包含十进制数字则返回True,否则返回False

>>> s='1234'
>>> s.isdecimal()
True
>>> s='ox12'#十六进制
>>> s.isdecimal()
False
>>> s='o123'#八进制
>>> s.isdigit()
False

14.islower() 如果字符中至少包含一个能区分大小写的字符,并且这些字符都是小写则返回True,否则返回Flase

 isupper()如果字符中至少包含一个能区分大小写的字符,并且这些字符都是大写则返回True,否则返回Flase

1 >>> s='ilovecnblog'
2 >>> s.islower()
3 True
4 >>> s='ILOVE'
5 >>> s.isupper()
6 True

15.isnumeric() 如果字符串只包含数字字符,则返回True,否则返回False

初一看感觉和isdigit()是一样的,但是:

 1 >>> num='1'
 2 >>> num.isdigit()
 3 True
 4 >>> num.isnumeric()
 5 True
 6 >>> num=b'1'
 7 >>> num.isdigit()
 8 True
 9 >>> num.isnumeric()
10 Traceback (most recent call last):
11   File "<pyshell#31>", line 1, in <module>
12     num.isnumeric()
13 AttributeError: 'bytes' object has no attribute 'isnumeric'
14 >>> num=''#汉字的数字,同样的还有罗马数字等
15 >>> num.isdigit()
16 False
17 >>> num.isnumeric()
18 True

17.isidentifier() 判断字符串是否包含该语言的保留字

'def'.isidentifier()
Out[3]: 
True
'eval'.isidentifier()
Out[4]: 
True

 18.isprintable() 判断字符串中所有的字符串都是可以通过repr表示成字符串,或者字符串是空的,都返回True,否则返回False

chr(1000000).isprintable()
Out[13]: 
False

 这里使用一个超出字符编码范围的数字去转化成字符,测试其是否可以打印,显然,答案是不行。

19.isspace() 判断字符串,至少有一个字符的字符串中所有字符是否都是空格,不是则返回False

''.isspace()
Out[14]: 
False
' '.isspace()
Out[15]: 
True
' a'.isspace()
Out[16]: 
False

 20.istitle() 判断是否是标题格式,这里理解为首字母大写。

'Author'.istitle()
Out[17]: 
True
'aA'.istitle()
Out[18]: 
False
'Aa'.istitle()
Out[19]: 
True
'AAAa'.istitle()
Out[20]: 
False

 21.isupper() 判断字符串是否全部是大写

'AAAa'.isupper()
Out[21]: 
False

 22.join() 返回一个用指定字符串分隔的字,或者是将指定字符加入到另一个字符中。

a = '12345'
','.join(a)
Out[23]: 
'1,2,3,4,5'

 23.lower() 返回的是指定字符串的拷贝,并转化成小写

'AAA'.lower()
Out[24]: 
'aaa'

 24.ljust() 可以指定宽度,以及填充字符串,返回的是按宽度,填充字符串格式化后的左对齐的字符串。

b = 'a'.ljust(10)
len(b)
Out[28]: 
10
'a'.ljust(10, 'A') # 指定以A填充
Out[30]: 
'aAAAAAAAAA'

 25.partition:在指定字符串中查找sep,如果找到了返回该字符前面的部分,sep,及后面的部分,

如果没找到则返回sep及两个空字符中,类似于split,但又有不同

'ssaafdaf'.partition('f')
Out[3]: 
('ssaa', 'f', 'daf')

 26.replace ,用指定字符串替换指定字符串,如果不指定替换次数,仅替换第一个。

'this is  a test'.replace('a', 'A')
Out[4]: 
'this is  A test'

 27.rfind(): 返回指定子串的最高索引,如果没找到则返回-1,可以指定要开始替换的起始,结束位置。

'this is a test'.rfind('i')
Out[5]: 
5

 28.rindex(),与上面的rfind一样,只是如果没找到不是返回-1,而是触发错误

'this is a test'.rindex('g')
Traceback (most recent call last):File "C:\Program Files\Python35\lib\site-packages\IPython\core\interactiveshell.py", line 2869, in run_codeexec(code_obj, self.user_global_ns, self.user_ns)File "<ipython-input-6-f8a393e6a7d2>", line 1, in <module>'this is a test'.rindex('g')
ValueError: substring not found

 29.rjust();与ljust()相对应

'aa'.ljust(10)
Out[25]: 
'aa        '
'aa'.rjust(10)
Out[26]: 
'        aa'

 30.rpartition()与partition一样,但是是从右边开始

'this is a test'.rpartition('a')
Out[7]: 
('this is ', 'a', ' test')

 31.rsplit(),与split作用相同,但是从右侧开始

this is a test'.rsplit(' ')
Out[8]: 
['this', 'is', 'a', 'test']

 但是讲真,如果不仔细考虑你是不会发现它与split有什么不同的,只有当你指定了最大切割次数时才会有效果。

'this is a test'.split(' ', 1)
Out[10]: 
['this', 'is a test']
'this is a test'.rsplit(' ', 1)
Out[11]:
['this is a', 'test']

 32.rstrip(), 从右侧移除指定字符

'this is a test'.rstrip('t')
Out[12]: 
'this is a tes'

 33.split(), 按指定字符串对目标字符串进行切割,可以指定切割次数

'this is a test'.split('i', 1)
Out[13]: 
['th', 's is a test']

 感觉它与partition的不同在于它返回的结果中移除了指定的字符串

34.splitlines(),返回字符串的行,按换行符切割,如果没指定keepends=True,则会将其从结果中移除

'this is a string\n this is a test'.splitlines()
Out[14]: 
['this is a string', ' this is a test']'this is a string\n this is a test'.splitlines(keepends=True)
Out[16]: 
['this is a string\n', ' this is a test']

 35.startswith(),判断字符串是否以某个字符开头

'this is a test'.startswith('t')
Out[18]: 
True
# 不一定非得一单个字符
'this is a test'.startswith('this')
Out[19]: 
True

 36.strip() 移除字符串两侧的指定字符串,默认移除空格,需要注意的是可以指定多个字符

'this is a test'.strip('ts')
Out[20]: 
'his is a te'

 37.swapcase() 转换大小写

'this is A test'.swapcase()
Out[21]: 
'THIS IS a TEST'

 38.title(), 标题格式,就是首字母大写,其它字符小写

'this is a test'.title()
Out[22]: 
'This Is A Test'

 39.upper(),将字符全部转成大写

'this is a test'.upper()
Out[24]: 
'THIS IS A TEST'

 40.zfill(),这里的z指zero,用0将字符填充到指定长度

'aa'.zfill(10)
Out[25]: 
'00000000aa'

 41.maketrans(),translate,因为内容比较多,见我另一博客

http://www.cnblogs.com/Andy963/p/7060292.html

posted on 2015-12-24 15:06 Andy_963 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/Andy963/p/5073128.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/419164.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

重学算法第三期|数据结构与算法001

目录 强烈推荐一个数据结构可视化工具&#xff1a;https://www.cs.usfca.edu/~galles/visualization/Algorithms.html&#xff0c;点击B树即可模拟B树的动态插入过程&#xff0c;非常有利于理解 1、开篇词 2、为什么要学习数据结构与算法 3、如何抓住重点&#xff0c;系统高…

部署和调优 3.4 腾讯企业邮箱免费版 未完

浏览器输入腾讯的企业邮箱官网 exmail.qq.com 点右上角的 申请开通 最下面有个 免费版 填好基本信息 根据提示验证密保邮箱 转载于:https://www.cnblogs.com/wangshaojun/p/5079304.html

前端学习(1715):前端系列javascript之页面配置

test-page.vue <template><view>test-page</view> </template><script>export default {data() {return {}},methods: {}} </script><style></style>page.json {"pages": [ //pages数组中第一项表示应用启动页&a…

03|复杂度分析(上):如何分析、统计算法的执行效率和资源消耗?

目录 为什么需要复杂度分析&#xff1f; 大 O 复杂度表示法 时间复杂度分析 几种常见时间复杂度 空间复杂度分析 为什么需要复杂度分析&#xff1f; 事后统计法&#xff1a;代码跑一遍&#xff0c;通过统计、监控&#xff0c;就能得到算法执行的时间和占用的内存大小。这种…

前端学习(1716):前端系列javascript之页面配置下

page.vue {"pages": [ //pages数组中第一项表示应用启动页&#xff0c;参考&#xff1a;https://uniapp.dcloud.io/collocation/pages{"path" : "pages/test-page/test-page","style" : {"navigationBarTitleText":"t…

04 | 复杂度分析(下):浅析最好、最坏、平均、均摊时间复杂度

// n表示数组array的长度 int find(int[] array, int n, int x) {int i 0;int pos -1;for (; i < n; i) {if (array[i] x) {pos i;break;}}return pos; } 这段代码的时间复杂度还是 O(n) 吗&#xff1f;如果数组中第一个元素正好是要查找的变量 x&#xff0c;那就不需要…

Atitit.java swing打印功能 api  attilax总结

Atitit.java swing打印功能 api attilax总结 1. 打印方式有三种&#xff1a;2 1.1. 一是不经过任何修改&#xff0c;直接调用javascript中的window.print()打印。2 1.2. 二根据客户要求的报表格式&#xff0c;编写相应格式的html&#xff0c;装载数据打印&#xff0c;同样调用…

git clone 速度过慢

由于公司内网限制&#xff0c;通过git clone mybatis的源码时速度贼慢 原来的方式&#xff1a;git clone ​​​​​​​https://github.com/mybatis/mybatis-3.git 超级慢——失败 改进方式&#xff1a;git clone https://github.com.cnpmjs.org/mybatis/mybatis-3.git 贼快…

2016/1/4 学习笔记 数据类型转换 注释 语句

⑤ 数据类型转换 自动转换&#xff1a; 一般在算术运算过程中进行自 动转换为数字类型比较大的类型 由低级到高级转换 强制转换&#xff1a;又叫做显示转换。 1&#xff0c;从高精…

前端学习(1718):前端系列javascript之生命周期上

<script>export default {onLaunch: function() {console.log(App Launch)//登录//用户信息//存储},onShow: function() {console.log(App Show)//时间戳//计算用胡得使用时间},onHide: function() {console.log(App Hide)//应用进入后台所作得得事情},onError(e){consol…

05 | 数组:为什么很多编程语言中数组都从0开始编号?

什么是数组&#xff1f; 数组&#xff08;Array&#xff09;是一种线性表数据结构。它用一组连续的内存空间&#xff0c;来存储一组具有相同类型的数据。 线性表存储结构连续内存空间存储相同类型数据 优点&#xff1a;连续内存相同类型数据数组可以实现随机访问 缺点&#…

远离你身边消极爱抱怨的人!!

跟着苍蝇你會找到厕所&#xff0c; 跟着蜜蜂你會找到花朵&#xff0c; 跟着千万赚百万&#xff0c; 跟着乞丐会要饭. 现实生活中&#xff0c; 你和谁在一起的确很重要&#xff0c; 甚至能改变你的成长轨迹&#xff0c; 决定你的人生成败。 和什么样的人在一起&#xff0c; 就会…

前端学习(1720):前端系列javascript之生命周期下

page2.vue <template><view>这是page2<button type"primary" click"open">点击跳转</button></view> </template><script>export default {data() {return {}},onLoad() {console.log(page onload2)},//页面渲…

LeetCode训练

缺失的正整数 /*** 0&#xff5e;n-1中缺失的数字*/ public class MissingNum {public int missingNumber(int[] nums) {int i 0;int j nums.length - 1;while (i < j) {int m i ((j - i) >> 2);if (nums[m] m) i m 1;else j m - 1;}return nums[i] i ? nu…

C#线程学习

齐全线程学习转载于:https://www.cnblogs.com/AiYaTou/p/5110712.html

06 | 链表(上):如何实现LRU缓存淘汰算法?

缓存 作用 缓存是一种提高数据读取性能的技术&#xff0c;在硬件设计、软件开发中都有着非常广泛的应用&#xff0c;比如常见的 CPU 缓存、数据库缓存、浏览器缓存等等。 淘汰策略 常见的策略有三种&#xff1a;先进先出策略 FIFO&#xff08;First In&#xff0c;First Ou…

C++处理一个动态规划的问题

嗯哼&#xff0c;别人问的问题&#xff0c;看的我也头晕&#xff0c;百度了一下动态规划&#xff0c;看了看才想起来该怎么做&#xff0c;今天写了写代码&#xff0c;实现了~ 要求是递归&#xff0c;动态规划&#xff0c;想了想这种方法也是最简单的~ 所谓动态规划&#xff1a;…

07 | 链表(下):如何轻松写出正确的链表代码?

目录 技巧一&#xff1a;理解指针或者引用的含义 技巧二&#xff1a;警惕指针丢失和内存泄漏 技巧三&#xff1a;利用哨兵简化实现难度 技巧四&#xff1a;重点留意边界条件处理 技巧五&#xff1a;举例画图&#xff0c;辅助思考 技巧六&#xff1a;多写多练&#xff0c;…

“睡服”面试官系列第二十篇之generator函数的异步应用(建议收藏学习)

目录 1. 传统方法 2. 基本概念 2.1异步 2.2回调函数 2.3Promise 3. Generator 函数 3.1协程 3.2协程的 Generator 函数实现 3.3Generator 函数的数据交换和错误处理 3.4异步任务的封装 4. Thunk 函数 4.1参数的求值策略 4.2Thunk 函数的含义 4.3JavaScript 语言的…