python基础(二)字符串內建函数详解
字符串
定义:它是一个有序的字符的集合,用于存储和表示基本的文本信息,‘’或“”或‘’‘ ’‘’中间包含的内容称之为字符串
特性:
1.只能存放一个值
2.不可变,只能重新赋值
3.按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序
字符串常用功能
移除空白
分割
长度
索引
切片
格式化输出
详细举例,上篇博文有写
字符常用內建函数
def capitalize(self): # real signature unknown; restored from __doc__
"""
B.capitalize() -> copy of B
把字符串的第一个字符大写
Return a copy of B with only its first character capitalized (ASCII)
and the rest lower-cased.
"""
pass def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
B.center(width[, fillchar]) -> copy of B
返回一个原字符串居中,并使用空格填充至长度width的新字符
Return B centered in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
pass def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.count(sub[, start[, end]]) -> int
返回str在string里面出现的次数,如果start或者end指定则返回指定范围内str出现的次数
Return the number of non-overlapping occurrences of subsection sub in
bytes B[start:end]. Optional arguments start and end are interpreted
as in slice notation.
"""
return 0 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
"""
S.encode(encoding='utf-8', errors='strict') -> bytes
以encoding 指定的编码格式解码string,如果出错默认报一个ValueError的异常,除非errors指定的是‘ignore’或者replace
Encode S using the codec registered for encoding. Default encoding
is 'utf-8'. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
"""
pass def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.endswith(suffix[, start[, end]]) -> bool
检查字符串是否以suffix结束,如果start或者end指定则检查指定的范围内是否以suffix结束,如果是返回True,否则返回False
Return True if B ends with the specified suffix, False otherwise.
With optional start, test B beginning at that position.
With optional end, stop comparing B at that position.
suffix can also be a tuple of bytes to try.
"""
return False def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
"""
B.expandtabs(tabsize=8) -> copy of B
把字符串string中的tab符号\t转换为空格,默认的空格数tabsize是8
Return a copy of B where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
"""
pass def insert(self, *args, **kwargs): # real signature unknown
"""
Insert a single item into the bytearray before the given index. index
The index where the value is to be inserted.
item
The item to be inserted.
"""
pass def isalnum(self): # real signature unknown; restored from __doc__
"""
B.isalnum() -> bool
如果string至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False
Return True if all characters in B are alphanumeric
and there is at least one character in B, False otherwise.
"""
return False def isalpha(self): # real signature unknown; restored from __doc__
"""
B.isalpha() -> bool
如果string至少有一个字符并且所有字符都是字母则返回True,否则返回False
Return True if all characters in B are alphabetic
and there is at least one character in B, False otherwise.
"""
return False def isdigit(self): # real signature unknown; restored from __doc__
"""
B.isdigit() -> bool
如果string只包含十进制数字则返回True,否则返回False
Return True if all characters in B are digits
and there is at least one character in B, False otherwise.
"""
return False def islower(self): # real signature unknown; restored from __doc__
"""
B.islower() -> bool
如果string中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True,否则返回False
Return True if all cased characters in B are lowercase and there is
at least one cased character in B, False otherwise.
"""
return False def isspace(self): # real signature unknown; restored from __doc__
"""
B.isspace() -> bool
如果string中只包含空格,则返回Ture,否则返回False
Return True if all characters in B are whitespace
and there is at least one character in B, False otherwise.
"""
return False def istitle(self): # real signature unknown; restored from __doc__
"""
B.istitle() -> bool
如果string是标题化的(就是首字母大写)则返回True,否则返回False
Return True if B is a titlecased string and there is at least one
character in B, i.e. uppercase characters may only follow uncased
characters and lowercase characters only cased ones. Return False
otherwise.
"""
return False def isupper(self): # real signature unknown; restored from __doc__
"""
B.isupper() -> bool
如果string中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回True,否则返回False
Return True if all cased characters in B are uppercase and there is
at least one cased character in B, False otherwise.
"""
return False def join(self, *args, **kwargs): # real signature unknown
"""
Concatenate any number of bytes/bytearray objects.
以string 作为分隔符,将序列中所有的元素(的字符串表示)合并为一个新的字符串
The bytearray whose method is called is inserted in between each pair. The result is returned as a new bytearray object.
"""
pass def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
B.ljust(width[, fillchar]) -> copy of B
返回一个原字符左对齐,并使用空格填充至长度width的新字符串
Return B left justified in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
pass def lower(self): # real signature unknown; restored from __doc__
"""
B.lower() -> copy of B
转换sting中所有大写字符为小写
Return a copy of B with all ASCII characters converted to lowercase.
"""
pass def maketrans(*args, **kwargs): # real signature unknown
"""
Return a translation table useable for the bytes or bytearray translate method. The returned table will be one where each byte in frm is mapped to the byte at
the same position in to. The bytes objects frm and to must be of the same length.
"""
pass def partition(self, sep): # real signature unknown; restored from __doc__
"""
S.partition(sep) -> (head, sep, tail)
有点像find()和split()的结合体,从str出现的第一个位置起,把字符串string分成一个三字符的元组(string_pre_str,str,
string_post_str),如果string中不包含str则string_pre_str == string.
Search for the separator sep in S, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
"""
pass def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return a single item from B. index
The index from where to remove the item.
-1 (the default value) means remove the last item. If no index argument is given, will pop the last item.
"""
pass def remove(self, *args, **kwargs): # real signature unknown
"""
Remove the first occurrence of a value in the bytearray. value
The value to remove.
"""
pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
"""
S.replace(old, new[, count]) -> str
把string中的old替换成new,如果count指定,则替换不超过count次
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
"""
return ""
def reverse(self, *args, **kwargs): # real signature unknown
""" Reverse the order of the values in B in place. """
pass def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.find(sub[, start[, end]]) -> int
检测str是否包含在string中,如果start和end指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1
Return the lowest index in B where subsection sub is found,
such that sub is contained within B[start,end]. Optional
arguments start and end are interpreted as in slice notation. Return -1 on failure.
"""
return 0 def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.rfind(sub[, start[, end]]) -> int
类似于find()函数,不过是从右边开始查找
Return the highest index in B where subsection sub is found,
such that sub is contained within B[start,end]. Optional
arguments start and end are interpreted as in slice notation. Return -1 on failure.
"""
return 0 def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.index(sub[, start[, end]]) -> int
跟find()方法一样,只不过如果str不在string中会报一个异常
Like B.find() but raise ValueError when the subsection is not found.
"""
return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.rindex(sub[, start[, end]]) -> int
类似于index(),不过是从右边开始
Like B.rfind() but raise ValueError when the subsection is not found.
"""
return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
B.rjust(width[, fillchar]) -> copy of B
返回一个原字符串右对齐,并使用空格填充至长度width的新字符串
Return B right justified in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
pass def rpartition(self, sep): # real signature unknown; restored from __doc__
"""
S.rpartition(sep) -> (head, sep, tail)
类似于partition()函数,不过是从右边开始查找
Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and S.
"""
pass def strip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.strip([chars]) -> str
删除string字符串左右两边的空格、\n回车
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return "" def rstrip(self, *args, **kwargs): # real signature unknown
"""
Strip trailing bytes contained in the argument.
删除string字符串末尾的空格
If the argument is omitted or None, strip trailing ASCII whitespace.
"""
pass def lstrip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.lstrip([chars]) -> str
截掉string左边的空格
Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return "" def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
"""
S.split(sep=None, maxsplit=-1) -> list of strings
以seq为分隔符切片string,与partition的区别结果不包含seq,如果maxsplit有指定值,仅分割maxsplit个字符串
Return a list of the words in S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are
removed from the result.
"""
return [] def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
"""
S.rsplit(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the
delimiter string, starting at the end of the string and
working to the front. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified, any whitespace string
is a separator.
"""
return [] def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
"""
S.splitlines([keepends]) -> list of strings
按照行分隔,返回一个包含各行作为元素的列表
Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
"""
return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.startswith(prefix[, start[, end]]) -> bool
检查字符串是否是以prefix开头,是则返回True,否则返回False。如果start和end指定值,则在指定范围内检查
Return True if B starts with the specified prefix, False otherwise.
With optional start, test B beginning at that position.
With optional end, stop comparing B at that position.
prefix can also be a tuple of bytes to try.
"""
return False def swapcase(self): # real signature unknown; restored from __doc__
"""
B.swapcase() -> copy of B
翻转string中大小写
Return a copy of B with uppercase ASCII characters converted
to lowercase ASCII and vice versa.
"""
pass def title(self): # real signature unknown; restored from __doc__
"""
S.title() -> str
返回“标题化”的string,就是说所有单词都是以大写开始,其余字母均为小写
Return a titlecased version of S, i.e. words start with title case
characters, all remaining cased characters have lower case.
"""
return "" def translate(self, table, deletechars=None): # real signature unknown; restored from __doc__
"""
translate(table, [deletechars])
根据table的表(包含256个字符)转换string的字符,要过滤掉的字符放到deletechars参数中
Return a copy with each character mapped by the given translation table. table
Translation table, which must be a bytes object of length 256. All characters occurring in the optional argument deletechars are removed.
The remaining characters are mapped through the given translation table.
"""
pass def upper(self): # real signature unknown; restored from __doc__
"""
B.upper() -> copy of B
转换string中的小写字母为大写
Return a copy of B with all ASCII characters converted to uppercase.
"""
pass def zfill(self, width): # real signature unknown; restored from __doc__
"""
B.zfill(width) -> copy of B
返回长度为width的字符串,原字符串string右对齐,前面填充0
Pad a numeric string B with zeros on the left, to fill a field
of the specified width. B is never truncated.
"""
pass def format(self, *args, **kwargs): # known special case of str.format
"""
S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
"""
pass def format_map(self, mapping): # real signature unknown; restored from __doc__
"""
S.format_map(mapping) -> str Return a formatted version of S, using substitutions from mapping.
The substitutions are identified by braces ('{' and '}').
"""
return "" def isidentifier(self): # real signature unknown; restored from __doc__
"""
S.isidentifier() -> bool Return True if S is a valid identifier according
to the language definition. Use keyword.iskeyword() to test for reserved identifiers
such as "def" and "class".
"""
return False
內建函数使用方法
>>> name = "wangeq"
>>> name.capitalize() #首字母大写
'Wangeq'
>>> name.center(50,'-') #返回原字符串居中
'----------------------wangeq----------------------'
>>> len(name.center(50,'-'))
50
>>> hello ="welcome to beijing"
>>> hello.count('i') #计数i在string出现的次数
2
>>> hello.encode() #将字符串编码成bytes格式
b'welcome to beijing'
>>> hello.endswith("ing") # 判断字符串是否以 ing结尾
True
>>> hello.endswith("wl")
False
>>> 'wang\teq'.expandtabs() #输出'wang eq', 将\t转换成多长的空格
'wang eq'
>>> hello.find('W') #查找W,找到返回其索引, 找不到返回-1
-1
>>> hello.find('w')
0
>>>
>>> 'wang12'.isalnum() #所有字符是否是字母或数字
True
>>> 'wang12#'.isalnum()
False
>>> 'wang12'.isalpha() #所有字符是否都是字母
False
>>> 'wang'.isalpha()
True
>>> ''.isdigit() #是否只包含十进制数字
True
>>> '0x122'.isdigit()
False
>>> ' '.isspace() #字符是否只包含空格
True
>>> 'Welcome To Beijing'.istitle() #是否标题化,首字母大写
True
>>> '|'.join(['wangeq','jack','rose']) #以 ‘|’ 作为分隔符,将序列中字符合并为一个字符
'wangeq|jack|rose'
>>> hello.ljust(50,"-") #左对齐字符串,指定50个字符,以“-”填充空格
'welcome to beijing--------------------------------'
>>> hello.rjust(50,"-") #右对齐
'--------------------------------welcome to beijing'
>>> "WANGeq".lower() #转换为小写
'wangeq'
>>> 'welcome to beijing'.replace('to','TO') #TO替换to
'welcome TO beijing'
>>> 'welcome to beijing'.index('i') #查找‘c’ 下标位置,从左开始
13
>>> 'welcome to beijing'.rindex('i') #查找‘c’ 下标位置,从右开始
15
>>> ' wang \n'.strip() #去掉字符串左右空格
'wang'
>>> ' wang \n'.rstrip()
' wang'
>>> ' wang \n'.lstrip()
'wang \n'
>>> 'WangisDDD'.swapcase() #翻转大小写字母
'wANGISddd'
>>> 'WNSNsssd ddd'.upper() #翻转字符串中小写为大写
'WNSNSSSD DDD'
>>> 'wangeq'.zfill(50) #返回长度为50字符串右对齐,前面填充0
'00000000000000000000000000000000000000000000wangeq'
format:
>>> msg = "my name is {},and age is {}"
>>> msg.format("wange",23)
'my name is wange,and age is 23'
>>> msg = "my name is {0},and age is {1}"
>>> msg.format("wange",24)
'my name is wangeq,and age is 24'
>>> msg = "my name is {name},and age is {age}"
>>> msg.format(age=23,name="wange")
'my name is wange,and age is 23'
format_map:
>>> msg = "my name is {name},and age is {age}"
>>> msg.format_map({'name':'wangeq','age':22})
'my name is wangeq,and age is 22'
maketrans:
>>> intab = 'abcdef'
>>> outtab = ''
>>> trantab = str.maketrans(intab, outtab)
>>> str = "this is string example...."
>>> str.translate(trantab)
'this is string 5x1mpl5....'
>>>
>>> c = "wangeq_ssdd" #检测一段字符串可否被当作标志符,即是否符合变量命名规则
>>> c.isidentifier()
True
python基础(二)字符串內建函数详解的更多相关文章
- Python学习进程(8)字符串內建函数
Python字符串內建函数实现了string模块的大部分方法,并包括了对Unicode编码方式的支持. (1)capitalize(): 将字符串的第一个字母变成大写,其他字母变小写. ...
- Python中的zip()与*zip()函数详解
前言 实验环境: Python 3.6: 示例代码地址:下载示例: 本文中元素是指列表.元组.字典等集合类数据类型中的下一级项目(可能是单个元素或嵌套列表). zip(*iterables)函数详解 ...
- 第四章:Python基础の快速认识內置函数和操作实战
本課主題 內置函数介紹和操作实战 装饰器介紹和操作实战 本周作业 內置函数介紹和操作实战 返回Boolean值的內置函数 all( ): 接受一個可以被迭代的對象,如果函数裡所有為真,才會真:有一個是 ...
- Python基础(二) —— 字符串、列表、字典等常用操作
一.作用域 对于变量的作用域,执行声明并在内存中存在,该变量就可以在下面的代码中使用. 二.三元运算 result = 值1 if 条件 else 值2 如果条件为真:result = 值1如果条件为 ...
- Python基础二字符串和变量
了解一下Python中的字符串和变量,和Java,c还是有点区别的,别的不多说,上今天学习的代码 Python中没有自增自减这一项,在转义字符那一块,\n,\r\n都是表示回车,但是对于不同的操作系统 ...
- python基础教程笔记—即时标记(详解)
最近一直在学习python,语法部分差不多看完了,想写一写python基础教程后面的第一个项目.因为我在网上看到的别人的博客讲解都并不是特别详细,仅仅是贴一下代码,书上内容照搬一下,对于当时刚学习py ...
- python 字符串的split()函数详解
split翻译为分裂. split()就是将一个字符串分裂成多个字符串组成的列表. split()当不带参数时以空格进行分割,当代参数时,以该参数进行分割. //---当不带参数时 example: ...
- python 字符串的split()函数详解(转)
作者:宋桓公 出处:http://www.cnblogs.com/douzi2/ 如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同 ...
- 【python基础】os.path模块常用方法详解
os.path模块 主要用于文件的属性获取,在编程中经常用到,以下是该模块的几种常用方法. 更多的方法可以去查看官方文档:http://docs.python.org/library/os.path. ...
随机推荐
- HDU 2489 Minimal Ratio Tree (DFS枚举+最小生成树Prim)
Minimal Ratio Tree Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other) ...
- java 线程的中断
Example12_6.java public class Example12_6 { public static void main(String args[]) { ClassRoom room6 ...
- Override/implements methods 如何添加
用过Eclipse 的ADT的都知道,要快速添加override或者implements方法,右键---Source---Override/Implements Method... 中文:右键---& ...
- Linux学习 -- Shell编程 -- 流程控制
if语句 单分支 if [ 条件判断式 ]; then 程序 fi 或者 if [ 条件判断式 ] then 程序 fi 例子: 双分支 if [ 条件判断式 ] then 程序 else 程序 fi ...
- vbs 截图
'VBS截屏.vbs ' Win7x64 测试通过(已安装Word2007): '参考: ' http://qtp.blogspot.com/2010/02/screenshot-vbscript ...
- Selenium2+python自动化28-table定位
前言 在web页面中经常会遇到table表格,特别是后台操作页面比较常见.本篇详细讲解table表格如何定位. 一.认识table 1.首先看下table长什么样,如下图,这种网状表格的都是table ...
- Windows Server 2003 下如何安装及配置 FTP 服务器(转)
Windows Server 2003 下如何安装及配置 FTP 服务器 一.安装 FTP 服务器组件: 写在这里的一点 : 安装及配置 FTP 服务器之前 , 必须先手工配置服务器本身的 IP 地址 ...
- 模态对话框 bootstrap-modal.js
调用方式 通过data属性 无需编写JavaScript代码即可生成一个对话框.在一个主控元素,例如按钮,上设置data-toggle="modal",然后再设置data-targ ...
- 2016大连网络赛 Football Games
Football Games Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) P ...
- 荐 android 如何打包自定义控件(转)
荐 android 如何打包自定义控件(转) 目录[-] 方式一:将项目打包成jar包 方式二:项目作为一个library 设计自定义的控件对android开发人员来说,是家常便饭了,但是多次做项 ...