day②:string内建方法
字符串内建方法:
string.expandtabs(tabsize=8) # tab符号转为空格 #默认8个空格
string.endswith(obj,beg=0,end=len(staring)) # 检测字符串是否已obj结束,如果是返回True #如果beg或end指定检测范围是否已obj结束
string.count(str,beg=0,end=len(string)) # 检测str在string里出现次数 f.count('\n',0,len(f)) 判断文件行数
string.find(str,beg=0,end=len(string)) # 检测str是否包含在string中
string.index(str,beg=0,end=len(string)) # 检测str不在string中,会报异常
string.isalnum() # 如果string至少有一个字符并且所有字符都是字母或数字则返回True
string.isalpha() # 如果string至少有一个字符并且所有字符都是字母则返回True
string.isnumeric() # 如果string只包含数字字符,则返回True
string.isspace() # 如果string包含空格则返回True
string.isupper() # 字符串都是大写返回True
string.islower() # 字符串都是小写返回True
string.lower() # 转换字符串中所有大写为小写
string.upper() # 转换字符串中所有小写为大写
string.lstrip() # 去掉string左边的空格
string.rstrip() # 去掉string字符末尾的空格
string.replace(str1,str2,num=string.count(str1)) # 把string中的str1替换成str2,如果num指定,则替换不超过num次
string.startswith(obj,beg=0,end=len(string)) # 检测字符串是否以obj开头
string.zfill(width) # 返回字符长度为width的字符,原字符串右对齐,前面填充0
string.isdigit() # 只包含数字返回True
string.split("分隔符") # 把string切片成一个列表
":".join(string.split()) # 以:作为分隔符,将所有元素合并为一个新的字符串
string.expandtabs(tabsize=8) # tab符号转为空格 #默认8个空格
string.endswith(obj,beg=0,end=len(staring)) # 检测字符串是否已obj结束,如果是返回True #如果beg或end指定检测范围是否已obj结束
string.count(str,beg=0,end=len(string)) # 检测str在string里出现次数 f.count('\n',0,len(f)) 判断文件行数
string.find(str,beg=0,end=len(string)) # 检测str是否包含在string中
string.index(str,beg=0,end=len(string)) # 检测str不在string中,会报异常
string.isalnum() # 如果string至少有一个字符并且所有字符都是字母或数字则返回True
string.isalpha() # 如果string至少有一个字符并且所有字符都是字母则返回True
string.isnumeric() # 如果string只包含数字字符,则返回True
string.isspace() # 如果string包含空格则返回True
string.isupper() # 字符串都是大写返回True
string.islower() # 字符串都是小写返回True
string.lower() # 转换字符串中所有大写为小写
string.upper() # 转换字符串中所有小写为大写
string.lstrip() # 去掉string左边的空格
string.rstrip() # 去掉string字符末尾的空格
string.replace(str1,str2,num=string.count(str1)) # 把string中的str1替换成str2,如果num指定,则替换不超过num次
string.startswith(obj,beg=0,end=len(string)) # 检测字符串是否以obj开头
string.zfill(width) # 返回字符长度为width的字符,原字符串右对齐,前面填充0
string.isdigit() # 只包含数字返回True
string.split("分隔符") # 把string切片成一个列表
":".join(string.split()) # 以:作为分隔符,将所有元素合并为一个新的字符串
例子:
(1)capitalize
def capitalize(self):""" 首字母变大写 """"""S.capitalize() -> stringReturn a copy of the string S with only its first charactercapitalized."""return "">>> name = 'yaobin'>>> name.capitalize()'Yaobin'
(2)center
def center(self, width, fillchar=None):""" 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """"""S.center(width[, fillchar]) -> stringReturn S centered in a string of length width. Padding isdone using the specified fill character (default is a space)"""return "">>> name.center(20)' yaobin '>>> name.center(20,"*")'*******yaobin*******'
(3)count
def count(self, sub, start=None, end=None):""" 子序列个数 """"""S.count(sub[, start[, end]]) -> intReturn the number of non-overlapping occurrences of substring sub instring S[start:end]. Optional arguments start and end are interpretedas in slice notation."""return 0>>> name="yaobinyaobin">>> name[0:1]'y'>>> name.count('s')0>>> name.count('y')2>>> name.count('y',0,10)2>>> name.count('y',0,5)1
(4)expandtabs
def expandtabs(self, tabsize=None):""" 将tab转换成空格,默认一个tab转换成8个空格 """"""S.expandtabs([tabsize]) -> stringReturn a copy of S where all tab characters are expanded using spaces.If tabsize is not given, a tab size of 8 characters is assumed."""return "">>> name = 'yao bin' #yao 和 bin之间有一个tab>>> name.expandtabs() #默认一个tab转化成8个空格'yao bin'>>> name.expandtabs(1) #也可以自己指定多少个空格'yao bin'>>> name.expandtabs(2)'yao bin'>>> name.expandtabs(3)'yao bin'>>> name.expandtabs(10)'yao bin'>>> name.expandtabs(20)'yao bin'
(5)find
def find(self, sub, start=None, end=None):""" 寻找子序列位置,如果没找到,返回 -1 """"""S.find(sub [,start [,end]]) -> intReturn the lowest index in S where substring sub is found,such that sub is contained within S[start:end]. Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure."""return 0>>> name='yaobin'>>> name.find('n')5>>> name.find('o')2>>> name.find('no') #找不到返回-1-1>>>>>>>>> name='yaobinyaobin'>>> name.find('n') #默认找到第一个5
(6)format
def format(*args, **kwargs): # known special case of str.format""" 字符串格式化,动态参数,将函数式编程时细说 """"""S.format(*args, **kwargs) -> stringReturn a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}')."""pass>>> name="i m {0}, age {1}">>> name'i m {0}, age {1}'>>> name.format('yaobin',24) #按顺序的占位'i m yaobin, age 24'>>> name="i m {0}, age {1}">>> li = [2222,3333]>>> name.format(*li) #按顺序的占位,传一个列表进去,记得要加*'i m 2222, age 3333'>>> name="i m {ss}, age {dd}">>> name.format(ss='yaobin',dd=25)'i m yaobin, age 25'>>> name.format(dd=25,ss='yaobin') #按名称的占位'i m yaobin, age 25'>>> dic={'ss':123,'dd':456}>>> name'i m {ss}, age {dd}'>>> name.format(**dic) #名称占位,传字典进去,记得加**'i m 123, age 456'
(7)index
def index(self, sub, start=None, end=None):""" 子序列位置,如果没找到,报错 """S.index(sub [,start [,end]]) -> intLike S.find() but raise ValueError when the substring is not found."""return 0>>> name = 'yaobin'>>> name.find('b')3>>> name.index('b')3>>> name.find('abc') #find找不到返回-1-1>>> name.index('abc') #index找不到,报错Traceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: substring not found#注意和find的区别,find找不到,返回-1,而index找不到,报错
(8)isalnum
def isalnum(self):""" 是否是字母和数字 """"""S.isalnum() -> boolReturn True if all characters in S are alphanumericand there is at least one character in S, False otherwise."""return False>>> name'yaobin'>>> name.isalnum()True>>> name = '你妹'>>> name.isalnum()False
(9)isalpha
def isalpha(self):""" 是否是字母 """"""S.isalpha() -> boolReturn True if all characters in S are alphabeticand there is at least one character in S, False otherwise."""return False>>> name = 'yaobin'>>> name'yaobin'>>> name.isalpha()True>>> name = 'yaobin234324'>>> name.isalpha()False>>> name = 'yaobin2'>>> name.isalpha()False>>> name = 'y2'>>> name.isalpha()False>>> name = '2'>>> name.isalpha()False>>> name = 'y'>>> name.isalpha()True
(10)isdigit
def isdigit(self):""" 是否是数字 """"""S.isdigit() -> boolReturn True if all characters in S are digitsand there is at least one character in S, False otherwise."""return False>>> name = 'yaobin'>>> name'yaobin'>>> name.isdigit()False>>> name = '123'>>> name.isdigit()True
(11)islower
def islower(self):""" 是否小写 """"""S.islower() -> boolReturn True if all cased characters in S are lowercase and there isat least one cased character in S, False otherwise."""return False>>> name ='yaobin'>>> name'yaobin'>>> name.islower()True>>> name ='Yaobin'>>> name.islower()False>>> name ='234'>>> name.islower()False
(12)title、istitle
def title(self):“”“转换成标题”“”"""S.title() -> stringReturn a titlecased version of S, i.e. words start with uppercasecharacters, all remaining cased characters have lowercase."""return ""def istitle(self):“”“是否标题”“”"""S.istitle() -> boolReturn True if S is a titlecased string and there is at least onecharacter in S, i.e. uppercase characters may only follow uncasedcharacters and lowercase characters only cased ones. Return Falseotherwise."""return False>>> name = 'yaobin haha'>>> name'yaobin haha'>>> name.title()'Yaobin Haha' #转换成标题>>> name'yaobin haha'>>> name.istitle() #判断是否标题False>>> name = 'Yaobin Haha'>>> name.istitle()True
(13)isupper
def isupper(self):“”“是否大写”“”"""S.isupper() -> boolReturn True if all cased characters in S are uppercase and there isat least one cased character in S, False otherwise."""return False>>> name = 'Yaobin Haha'>>>>>> name.isupper()False>>> name = 'YAOBIN'>>> name.isupper()True
(14)join
def join(self, iterable):""" 连接 """"""S.join(iterable) -> stringReturn a string which is the concatenation of the strings in theiterable. The separator between elements is S."""return "">>> li = ['s1','s2']>>> '_'.join(li)'s1_s2'
(15)lower、upper、swapcase
def lower(self):""" 变小写 """"""S.lower() -> stringReturn a copy of the string S converted to lowercase."""return ""def upper(self):“”“变大写”“”"""S.upper() -> stringReturn a copy of the string S converted to uppercase."""return ""def swapcase(self):""" 大写变小写,小写变大写 """"""S.swapcase() -> stringReturn a copy of the string S with uppercase charactersconverted to lowercase and vice versa."""return "">>> name ="YAOBIN">>> name.lower() #变大写'yaobin'>>> name ="yaobin">>> name.upper() #变大写'YAOBIN'>>> name ="yaobin HAHA">>> name.swapcase() #大写变小写,小写变大写'YAOBIN haha'
(16)lstrip、rstrip、strip
def lstrip(self, chars=None):""" 移除左侧空白 """"""S.lstrip([chars]) -> string or unicodeReturn a copy of the string S with leading whitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping"""return ""def rstrip(self, chars=None):""" 移除右侧空白 """"""S.rstrip([chars]) -> string or unicodeReturn a copy of the string S with trailing whitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping"""return ""def strip(self, chars=None):""" 移除两段空白 """"""S.strip([chars]) -> string or unicodeReturn a copy of the string S with leading and trailingwhitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping"""return "">>> string01=" this my love ">>> string01.lstrip()'this my love '>>> string01.rstrip()' this my love'>>> string01.strip()'this my love'
(17)partition
def partition(self, sep):""" 分割,前,中,后三部分 """"""S.partition(sep) -> (head, sep, tail)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 notfound, return S and two empty strings."""pass>>> name'yaobin HAHA'>>> name.partition('in')('yaob', 'in', ' HAHA')
(18)replace
def replace(self, old, new, count=None):""" 替换 """"""S.replace(old, new[, count]) -> stringReturn a copy of string S with all occurrences of substringold replaced by new. If the optional argument count isgiven, only the first count occurrences are replaced."""return "">>> name'yaobin HAHA'>>> name.replace('bin','biao')'yaobiao HAHA'>>> name = 'yaobin yaobin yaobin'>>> name.replace('o','aaaaa') #会替换全部'yaaaaaabin yaaaaaabin yaaaaaabin'
(19)split
def split(self, sep=None, maxsplit=None):""" 分割, maxsplit最多分割几次 """"""S.split([sep [,maxsplit]]) -> list of stringsReturn a list of the words in the string S, using sep as thedelimiter string. If maxsplit is given, at most maxsplitsplits are done. If sep is not specified or is None, anywhitespace string is a separator and empty strings are removedfrom the result."""return []>>> name'thisis a python script'>>> name.split()['thisis', 'a', 'python', 'script']
(20)startswith、endswith
def startswith(self, prefix, start=None, end=None):""" 是否起始 """"""S.startswith(prefix[, start[, end]]) -> boolReturn True if S starts with the specified prefix, False otherwise.With optional start, test S beginning at that position.With optional end, stop comparing S at that position.prefix can also be a tuple of strings to try."""return Falsedef endswith(self, suffix, start=None, end=None):""" 是否以 xxx 结束 """"""S.endswith(suffix[, start[, end]]) -> boolReturn True if S ends with the specified suffix, False otherwise.With optional start, test S beginning at that position.With optional end, stop comparing S at that position.suffix can also be a tuple of strings to try."""return False>>> name = "my name is yaobin">>> name.startswith('my')True>>> name.startswith('dfdfdfdfd')False>>> name.endswith('yaobin')True>>> name.endswith('yao')False
(21)zfill
def zfill(self, width):"""方法返回指定长度的字符串,原字符串右对齐,前面填充0。""""""S.zfill(width) -> stringPad a numeric string S with zeros on the left, to fill a fieldof the specified width. The string S is never truncated."""return "">>> name.zfill(1)'my name is yaobin'>>> name.zfill(2)'my name is yaobin'>>> name.zfill(17)'my name is yaobin'>>> name.zfill(18)'0my name is yaobin'>>> name.zfill(19)'00my name is yaobin'>>> name.zfill(20)'000my name is yaobin'
(22)ljust、rjust
def ljust(self, width, fillchar=None):""" 内容左对齐,右侧填充 """"""S.ljust(width[, fillchar]) -> stringReturn S left-justified in a string of length width. Padding isdone using the specified fill character (default is a space)."""return ""def rjust(self, width, fillchar=None):""" 内容右对齐,左侧填充 """"""S.rjust(width[, fillchar]) -> stringReturn S right-justified in a string of length width. Padding isdone using the specified fill character (default is a space)"""return "">>> name ="yaobin hahah">>> name.ljust(13,"=") #指定字符宽度'yaobin hahah='>>> name.ljust(14,"=")'yaobin hahah=='>>> name.ljust(15,"=")'yaobin hahah==='>>> name.ljust(16,"=")'yaobin hahah===='>>> name.ljust(17,"=")'yaobin hahah====='>>> name.ljust(18,"=")'yaobin hahah======'>>> name ="yaobin hahah">>> name.rjust(13,"=")#指定字符宽度'=yaobin hahah'>>> name.rjust(15,"=")'===yaobin hahah'>>> name.rjust(16,"=")'====yaobin hahah'>>> name.rjust(17,"=")'=====yaobin hahah'>>> name.rjust(18,"=")'======yaobin hahah'
(23)translate
def translate(self, table, deletechars=None):"""转换,需要先做一个对应表,deletechars表示删除字符集合>>> import string>>> intab = "aeiou">>> outtab = "12345">>> trantab = string.maketrans(intab, outtab)>>> str = "this is string example....wow!!!">>> print str.translate(trantab, 'xm')th3s 3s str3ng 21pl2....w4w!!!""""""S.translate(table [,deletechars]) -> stringReturn a copy of the string S, where all characters occurringin the optional argument deletechars are removed, and theremaining characters have been mapped through the giventranslation table, which must be a string of length 256 or None.If the table argument is None, no translation is applied andthe operation simply removes the characters in deletechars."""return ""
end
浙公网安备 33010602011771号