python 字符串操作二 内建函数
一、查看字符串的内建函数
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
In [1]: a = '123' In [2]: a.
a.capitalize a.endswith a.index a.isidentifier a.istitle a.lstrip a.rindex a.split a.title
a.casefold a.expandtabs a.isalnum a.islower a.isupper a.maketrans a.rjust a.splitlines a.translate
a.center a.find a.isalpha a.isnumeric a.join a.partition a.rpartition a.startswith a.upper
a.count a.format a.isdecimal a.isprintable a.ljust a.replace a.rsplit a.strip a.zfill
a.encode a.format_map a.isdigit a.isspace a.lower a.rfind a.rstrip a.swapcase
二、常用的字符串内建函数
1、capitalize,字符串的第一个字符大写
>>> a = 'today is a good day.'
>>> a.capitalize()
'Today is a good day.'
2、 casefold,将所有字符小写,Unicode所有字符均适用
>>> b
'TODAY IS A GOOD DAY.'
>>> b.casefold()
'today is a good day.'
3、lower,将所有字符小写,只适用ASCii
>>> b
'TODAY IS A GOOD DAY.'
>>> b.lower()
'today is a good day.'
4、upper,将所有字符大写
>>> a
'today is a good day.'
>>> a.upper()
'TODAY IS A GOOD DAY.'
5、center,返回一个原字符串居中,并使用空格填充至长度 width 的新字符串,语法:str.center(width[, fillchar])
>>> a
'today is a good day.'
>>> a.center(40)
' today is a good day. '
6、count,用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置,语法:str.count(sub, start= 0,end=len(string))
>>> a
'today is a good day.'
>>> a.count('a')
3
>>> a.count('a', 5, -2)
2
7、encode,以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案,语法:str.encode(encoding='UTF-8',errors='strict')
errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。
>>> c = '你好'
>>> c.encode(encoding='utf-8')
b'\xe4\xbd\xa0\xe5\xa5\xbd'
8、decode,以 encoding 指定的编码格式解码字符串。默认编码为字符串编码,语法:str.decode(encoding='UTF-8',errors='strict')
>>> d
b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> d.decode(encoding='utf-8')
'你好'
9、startwith,检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查,语法:str.startswith(str, beg=0,end=len(string))
>>> a
'today is a good day.'
>>> a.startswith('today')
True
>>> a.startswith('day')
False
>>> a.startswith('day', 5)
False
>>> a.startswith('today', 5)
False
10、endwith,判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置,语法:str.endswith(suffix[, start[, end]])
>>> a
'today is a good day.'
>>> a.endswith('day.')
True
>>> a.endswith('today.')
False
>>> a.endswith('day.', 5)
True
11、expandtabs,把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8,语法:str.expandtabs(tabsize=8)
>>> e = ' today is a good day. '
>>> e
'\ttoday is \ta good day.\t\t'
>>> e.expandtabs(4)
' today is a good day. '
12、find,检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1,语法:str.find(str, beg=0, end=len(string))
>>> a
'today is a good day.'
>>> a.find('a')
3
>>> a.find('a', 10)
17
>>> a.find('abc')
-1
13、index,检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不存在 string中会报一个异常,语法:str.index(str, beg=0, end=len(string))
>>> a
'today is a good day.'
>>> a.index('a')
3
>>> a.index('a', 10)
17
>>> a.index('abc', 10)
Traceback (most recent call last):
File "<console>", line 1, in <module>
ValueError: substring not found
14、isalnum,检测字符串是否由字母和数字组成
>>> a = 'wang512'
>>> a.isalnum()
True
>>> a = 'wang'
>>> a.isalnum()
True
>>> a = '512'
>>> a.isalnum()
True
>>> a = 'wang 512'
>>> a.isalnum()
False
15、isalnum,检测字符串是否只由字母组成
>>> a = 'wang'
>>> a.isalpha()
True
>>> a = '512'
>>> a.isalpha()
False
16、isdecimal ,检查字符串是否只包含十进制字符。这种方法只存在于unicode对象
>>> a = '12345'
>>> a.isdecimal()
True
>>> a = 'wang'
>>> a.isdecimal()
False
17、isdigit,检测字符串是否只由数字组成
>>> a = '12345'
>>> a.isdigit()
True
>>> a = 'wang'
>>> a.isdigit()
False
18、isidentifier,检测字符串是否以字母开头
>>> a.isidentifier()
False
>>> a = 'wang'
>>> a.isidentifier()
True
19、islower,检测字符串是否由小写字母组成。
>>> a = "wang"
>>> a.islower()
True
>>> a = "Wang"
>>> a.islower()
False
20、isupper,检测字符串中所有的字母是否都为大写。
>>> a = "WANG"
>>> a.isupper()
True
>>> a = "Wang"
>>> a.isupper()
False
21、isnumeric,检测字符串是否只由数字组成。这种方法是只针对unicode对象。
>>> a = '12345'
>>> a.isnumeric()
True
>>> a = 'w123'
>>> a.isnumeric()
False
22、isprintable,包含所有可打印字符的字符串。
23、isspace,检测字符串是否只由空格组成。
24、istitile,检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。
25、join,将序列中的元素以指定的字符连接生成一个新的字符串,语法:str.join(sequence)
>>> a = ['a', 'b', 'c', 'd']
>>> ','.join(a)
'a,b,c,d'
26、ljust,返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串,语法:str.ljust(width[, fillchar])
>>> a = 'wang'
>>> a.ljust(10, '>')
'wang>>>>>>'
27、rjust,返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串,语法:str.rjust(width[, fillchar])
>>> a = 'wang'
>>> a.rjust(10, '<')
'<<<<<<wang'
28、split,通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串,语法:str.split(str="", num=string.count(str)).
>>> a = 'wang wang wang wang'
>>> a.split('a', 3)
['w', 'ng w', 'ng w', 'ng wang']
29、rsplit
>>> a
'wang wang wang wang'
>>> a.rsplit('a', 3)
['wang w', 'ng w', 'ng w', 'ng']
30、splitlines,按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符,语法:str.splitlines([keepends])
>>> a = 'ab c\n\nde fg\rkl\r\n'
>>> a.splitlines()
['ab c', '', 'de fg', 'kl']
>>> a.splitlines(False)
['ab c', '', 'de fg', 'kl']
>>> a.splitlines(True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
31、strip,用于移除字符串头尾指定的字符(默认为空格),语法:str.strip([chars])
32、rstrip,删除 string 字符串末尾的指定字符(默认为空格),语法:str.rstrip([chars])
33、lstrip,用于截掉字符串左边的空格或指定字符,语法:str.lstrip([chars])
34、maketrans,用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标,语法:str.maketrans(intab, outtab)
注:两个字符串的长度必须相同,为一一对应的关系。
35、translate,根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中,语法:str.translate(table[, deletechars]);
>>> intab = "aeiou"
>>> outtab = "12345"
>>> trantab = str.maketrans(intab, outtab)
>>> s = 'abcdef'
>>> s.translate(trantab)
'1bcd2f'
>>> trantab
{97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
36、partition,用来根据指定的分隔符将字符串进行分割。如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。语法:str.partition(str)
37、rpartition
>>> a = "http://www.baidu.com ://sina"
>>> a.partition('://')
('http', '://', 'www.baidu.com ://sina')
>>> a.rpartition('://')
('http://www.baidu.com ', '://', 'sina')
38、replace,把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。语法:str.replace(old, new[, max])
str = "this is string example....wow!!! this is really string"
print(str.replace("is", "was"))
print(str.replace("is", "was", 3))
39、rfind,字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1。语法:str.rfind(str, beg=0 end=len(string))
str = "this is really a string example....wow!!!"
substr = "is" print(str.rfind(substr))
print(str.rfind(substr, 0, 10))
print(str.rfind(substr, 10, 0)) print(str.find(substr))
print(str.find(substr, 0, 10))
print(str.find(substr, 10, 0))
40、rindex,返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。语法:str.rindex(str, beg=0 end=len(string))
str1 = "this is string example....wow!!!"
str2 = "is" print(str1.rindex(str2))
print(str1.index(str2))
41、swapcase,用于对字符串的大小写字母进行转换。
42、title,返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())。
str = "this is string example....wow!!!"
print(str.title())
43、zfill,指定长度的字符串,原字符串右对齐,前面填充0。语法:str.zfill(width)
str = "this is string example....wow!!!"
print(str.zfill(40))
python 字符串操作二 内建函数的更多相关文章
- Python 字符串操作
Python 字符串操作(string替换.删除.截取.复制.连接.比较.查找.包含.大小写转换.分割等) 去空格及特殊符号 s.strip() .lstrip() .rstrip(',') 复制字符 ...
- python字符串操作实方法大合集
python字符串操作实方法大合集,包括了几乎所有常用的python字符串操作,如字符串的替换.删除.截取.复制.连接.比较.查找.分割等,需要的朋友可以参考下: #1.去空格及特殊符号 s.st ...
- 转 Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
转自: http://www.cnblogs.com/huangcong/archive/2011/08/29/2158268.html 黄聪:Python 字符串操作(string替换.删除.截取. ...
- Python 字符串操作及string模块使用
python的字符串操作通过2部分的方法函数基本上就可以解决所有的字符串操作需求: python的字符串属性函数 python的string模块 1.字符串属性方法操作: 1.>字符串格式输出对 ...
- python字符串操作总结
python中有各种字符串操作,一开始python有个专门的string模块,要使用需先import string.后来从python2.0开始,string方法改用str.method()形式调用, ...
- 『无为则无心』Python序列 — 17、Python字符串操作常用API
目录 1.字符串的查找 @1.find()方法 @2.index()方法 @3.rfind()和rindex()方法 @4.count()方法 2.字符串的修改 @1.replace()方法 @2.s ...
- python 字符串操作。。
#字符串操作 以0开始,有负下标的使用0第一个元素,-1最后一个元素,-len第一个元 素,len-1最后一个元素 name= "qwe , erw, qwe "print(nam ...
- Python 字符串操作,截取,长度
1.字符串操作: 字符串长度: s = "; slen = len(s); 字符串截取: print s[:-:-] #截取,逆序隔1个取一个字符 print s[:-:-] #截取,逆序隔 ...
- python字符串操作、文件操作,英文词频统计预处理
1.字符串操作: 解析身份证号:生日.性别.出生地等. 凯撒密码编码与解码 网址观察与批量生成 解析身份证号:生日.性别.出生地等 def function3(): print('请输入身份证号') ...
随机推荐
- IOS自己主动布局中的浮动布局(6)----MyFloatLayout横空出世
https://github.com/youngsoft/MyLinearLayout 前言 在MyLayout的6大布局中,每种布局都有不同的应用场景. 且每种布局的子视图的约束机制不一样:线性布局 ...
- [LeetCode] 038. Count and Say (Easy) (C++/Python)
索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 038. Cou ...
- HTTP的上传文件实例分析
这个是http文件传输的一种格式,当时不知道这种格式,废弃. HTTP的上传文件实例分析 由于论坛不支持Word写文章发帖. 首先就是附件发送怎么搞,这个必须解决.论坛是php的.我用Chrome类浏 ...
- AML LCD debuged
root@k101:/ # cat /sys/class/lcd/debug Usage: echo basi ...
- 用python编写的定向arp欺骗工具
刚学习了scapy模块的一些用法,非常强大,为了练手,利用此模块编写了一个arp欺骗工具,其核心是构造arp欺骗包.加了一个-a参数用于进行全网欺骗,先暂不实现.代码如下: #--*--coding= ...
- iOS优秀博文合集
一.优化篇 Xcode7中你一定要知道的炸裂调试神技 iOS使用Instrument-Time Profiler工具分析和优化性能问题 dSYM 文件分析工具 二.功能篇 3分钟实现iOS语言本地化/ ...
- Mac使用小结
1.修改pip的镜像地址及更新pip https://www.cnblogs.com/techroad4ca/p/5922389.html 2.更新python的库,比如更新six sudo pip ...
- 用Java编写的http下载工具类,包含下载进度回调
HttpDownloader.java package com.buyishi; import java.io.FileOutputStream; import java.io.IOException ...
- RubyMine安装、破解
经常安装东西,这是我安装过最快的ide破解版. 下载地址: http://www.jetbrains.com/ruby/download/index.html 破解序列号: name: rubymin ...
- MRP-MD04 中的函数
1.需求溯源 : MD_PEGGING_NODIALOG 2.实时库存 : MD_STOCK_REQUIREMENTS_LIST_API 这个函数中MDPSX 和 MDEZX 是通过 MDPS 的 I ...