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()) # 以:作为分隔符,将所有元素合并为一个新的字符串
def capitalize(self):
""" 首字母变大写 """
"""
S.capitalize() -> string
Return a copy of the string S with only its first character
capitalized.
"""
return""
>>> name =‘yaobin‘
>>> name.capitalize()
‘Yaobin‘
def center(self, width, fillchar=None):
""" 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
"""
S.center(width[, fillchar]) -> string
Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
return""
>>> name.center(20)
‘ yaobin ‘
>>> name.center(20,"*")
‘*******yaobin*******‘
def count(self, sub, start=None, end=None):
""" 子序列个数 """
"""
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are interpreted
as in slice notation.
"""
return0
>>> 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
""" 将tab转换成空格,默认一个tab转换成8个空格 """
"""
S.expandtabs([tabsize]) -> string
Return 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‘
def find(self, sub, start=None, end=None):
""" 寻找子序列位置,如果没找到,返回 -1 """
"""
S.find(sub [,start [,end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return0
>>> name=‘yaobin‘
>>> name.find(‘n‘)
5
>>> name.find(‘o‘)
2
>>> name.find(‘no‘)#找不到返回-1
-1
>>>
>>>
>>> name=‘yaobinyaobin‘
>>> name.find(‘n‘)#默认找到第一个
5
def format(*args,**kwargs):# known special case of str.format
""" 字符串格式化,动态参数,将函数式编程时细说 """
"""
S.format(*args, **kwargs) -> string
Return 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‘
def index(self, sub, start=None, end=None):
""" 子序列位置,如果没找到,报错 """
S.index(sub [,start [,end]])-> int
Like S.find() but raiseValueError when the substring isnot 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找不到,报错
def isalnum(self):
""" 是否是字母和数字 """
"""
S.isalnum() -> bool
Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
"""
returnFalse
>>> name
‘yaobin‘
>>> name.isalnum()
True
>>> name =‘你妹‘
>>> name.isalnum()
False
def isalpha(self):
""" 是否是字母 """
"""
S.isalpha() -> bool
Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
"""
returnFalse
>>> 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
def isdigit(self):
""" 是否是数字 """
"""
S.isdigit() -> bool
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
"""
returnFalse
>>> name =‘yaobin‘
>>> name
‘yaobin‘
>>> name.isdigit()
False
>>> name =‘123‘
>>> name.isdigit()
True
def islower(self):
""" 是否小写 """
"""
S.islower() -> bool
Return True if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
"""
returnFalse
>>> name =‘yaobin‘
>>> name
‘yaobin‘
>>> name.islower()
True
>>> name =‘Yaobin‘
>>> name.islower()
False
>>> name =‘234‘
>>> name.islower()
False
def title(self):
“”“转换成标题”“”
"""
S.title() -> string
Return a titlecased version of S, i.e. words start with uppercase
characters, all remaining cased characters have lowercase.
"""
return""
def istitle(self):
“”“是否标题”“”
"""
S.istitle() -> bool
Return True if S is a titlecased string and there is at least one
character in S, i.e. uppercase characters may only follow uncased
characters and lowercase characters only cased ones. Return False
otherwise.
"""
returnFalse
>>> name =‘yaobin haha‘
>>> name
‘yaobin haha‘
>>> name.title()
‘Yaobin Haha‘#转换成标题
>>> name
‘yaobin haha‘
>>> name.istitle()#判断是否标题
False
>>> name =‘Yaobin Haha‘
>>> name.istitle()
True
def isupper(self):
“”“是否大写”“”
"""
S.isupper() -> bool
Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
"""
returnFalse
>>> name =‘Yaobin Haha‘
>>>
>>> name.isupper()
False
>>> name =‘YAOBIN‘
>>> name.isupper()
True
def join(self, iterable):
""" 连接 """
"""
S.join(iterable) -> string
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
"""
return""
>>> li =[‘s1‘,‘s2‘]
>>>‘_‘.join(li)
‘s1_s2‘
def lower(self):
""" 变小写 """
"""
S.lower() -> string
Return a copy of the string S converted to lowercase.
"""
return""
def upper(self):
“”“变大写”“”
"""
S.upper() -> string
Return a copy of the string S converted to uppercase.
"""
return""
def swapcase(self):
""" 大写变小写,小写变大写 """
"""
S.swapcase() -> string
Return a copy of the string S with uppercase characters
converted to lowercase and vice versa.
"""
return""
>>> name ="YAOBIN"
>>> name.lower()#变大写
‘yaobin‘
>>> name ="yaobin"
>>> name.upper()#变大写
‘YAOBIN‘
>>> name ="yaobin HAHA"
>>> name.swapcase()#大写变小写,小写变大写
‘YAOBIN haha‘
def lstrip(self, chars=None):
""" 移除左侧空白 """
"""
S.lstrip([chars]) -> string or unicode
Return 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 unicode
Return 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 unicode
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.
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‘
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 not
found, return S and two empty strings.
"""
pass
>>> name
‘yaobin HAHA‘
>>> name.partition(‘in‘)
(‘yaob‘,‘in‘,‘ HAHA‘)
def replace(self, old, new, count=None):
""" 替换 """
"""
S.replace(old, new[, count]) -> string
Return a copy of string 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""
>>> name
‘yaobin HAHA‘
>>> name.replace(‘bin‘,‘biao‘)
‘yaobiao HAHA‘
>>> name =‘yaobin yaobin yaobin‘
>>> name.replace(‘o‘,‘aaaaa‘)#会替换全部
‘yaaaaaabin yaaaaaabin yaaaaaabin‘
def split(self, sep=None, maxsplit=None):
""" 分割, maxsplit最多分割几次 """
"""
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string 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[]
>>> name
‘thisis a python script‘
>>> name.split()
[‘thisis‘,‘a‘,‘python‘,‘script‘]
def startswith(self, prefix, start=None, end=None):
""" 是否起始 """
"""
S.startswith(prefix[, start[, end]]) -> bool
Return 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.
"""
returnFalse
def endswith(self, suffix, start=None, end=None):
""" 是否以 xxx 结束 """
"""
S.endswith(suffix[, start[, end]]) -> bool
Return 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.
"""
returnFalse
>>> name ="my name is yaobin"
>>> name.startswith(‘my‘)
True
>>> name.startswith(‘dfdfdfdfd‘)
False
>>> name.endswith(‘yaobin‘)
True
>>> name.endswith(‘yao‘)
False
def zfill(self, width):
"""方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""
"""
S.zfill(width) -> string
Pad a numeric string S with zeros on the left, to fill a field
of 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‘
def ljust(self, width, fillchar=None):
""" 内容左对齐,右侧填充 """
"""
S.ljust(width[, fillchar]) -> string
Return S left-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
return""
def rjust(self, width, fillchar=None):
""" 内容右对齐,左侧填充 """"""
S.rjust(width[, fillchar]) -> string
Return S right-justified in a string of length width. Padding is
done 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‘
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]) -> string
Return a copy of the string S, where all characters occurring
in the optional argument deletechars are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256 or None.
If the table argument is None, no translation is applied and
the operation simply removes the characters in deletechars.
"""
return""
原文:http://www.cnblogs.com/binhy0428/p/5125930.html