- def capitalize(self): , 首字母大写函数
- . casefold() 与 lower() 均为全部小写函数
区别:
汉语 & 英语环境下面,继续用 lower()没问题;要处理其它语言且存在大小写情况的时候再用casefold()
s = 'ABcD EfgH'
print('# s = ', s)
print('# s.casefold() = ', s.casefold())
print('# s.lower() = ', s.lower())
# s = ABcD EfgH
# s.casefold() = abcd efgh
# s.lower() = abcd efgh
- def center(self, width, fillchar=None): 以width宽度居中,以fillchar填充
- def ljust(self, width, fillchar=None): 字符串放左边
- def rjust(self, width, fillchar=None): 字符串放右边
- def zfill(self, width): 以0在左边填充
s = 'abc'
print('# s.center(20):', s.center(20))
print('# s.center(20, "*"): ', s.center(20, '*'))
print('# length of s.center(20) is: ', len(s.center(20)))
# s.center(20): abc
# s.center(20, "*"): ********abc*********
# length of s.center(20) is: 20
str14 = '25'
print(str14.zfill(5)) # 00025
- def count(self, sub, start=None, end=None):
- 只有参数sub,表示找出sub子串(可以为单个字符,也可以为字符串)出现的次数
- sub和start,表示从主字符串下标第start开始,返回sub子串出现的次数
- 都有,表示从下标第start开始到第end结束,返回sub子串出现的次
str1 = 'abcde ab 123 456 ab'
print('"ab"出现了:', str1.count('ab'))
print('"ab"从下标1开始出现了:', str1.count('ab', 1))
print('"ab"从下标-9开始出现了(不包括最后一个下标):', str1.count('ab', -9, -1))
"ab"出现了: 3
"ab"从下标1开始出现了: 2
"ab"从下标-9开始出现了(不包括最后一个下标): 0
- def encode(self, encoding=’utf-8’, errors=’strict’):
def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
"""
S.encode(encoding='utf-8', errors='strict') -> bytes
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.
"""
return b""
- def endswith(self, suffix, start=None, end=None):
- def startswith(self, prefix, start=None, end=None):
- 返回S[start:end]是不是以子串suffix结尾的(start和end可选)
str1 = 'abcde ab 123 456 ab'
print('str1是否以"ab"结尾:', str1.endswith('ab'))
print('str1[2:]是否以"ab"结尾:', str1.endswith('ab', 2))
print('str1[2:-1]是否以"ab"结尾:', str1.endswith('ab', 2, -1))
str1是否以"ab"结尾: True
str1[2:]是否以"ab"结尾: True
str1[2:-1]是否以"ab"结尾: False
def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
"""
S.expandtabs(tabsize=8) -> str
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 ""
- def find(self, sub, start=None, end=None):
def index(self, sub, start=None, end=None):
表示返回S[start,end]中sub第一次出现的位置,没有find函数返回-1,index函数抛出异常def rfind(self, sub, start=None, end=None):
- def rindex(self, sub, start=None, end=None):
str1 = 'abcde ab 123 456 ab'
print(str1.find('ab')) # 0
print(str1.index('ab')) # 0
print(str1.find('ab', 1)) # S[1:] 6
print(str1.index('ab', 1)) # S[1:] 6
print(str1.find('ab', 9, )) # S[9:] 17
print(str1.index('ab', 9, )) # S[9:] 17
print(str1.find('ab', 9, -1)) # S[9:-1] -1
print(str1.index('ab', 9, -1)) # S[9:-1] error
Traceback (most recent call last):
File "E:/examples of coding/python/s12/day3/temp.py", line 31, in <module>
print(str1.index('ab', 9, -1)) # S[9:-1] -1
ValueError: substring not found
- def format(self, *args, **kwargs):
表示字符串格式化,第一个参数为元组,第二个参数为字典
str3 = '{0}, {1}, {0}'
l = ['xujie', 'chenhuan']
print(str3.format('xujie', 'chenhuan'))
print(str3.format(*l))
str4 = '{0}, {1}, {0}, {name}, {age}'
dic = {'name':'anyiji', 'age':300}
print(str4.format('xujie', 'chenhuan', name='anyiji', age=300))
print(str4.format(*l, **dic))
# xujie, chenhuan, xujie
# xujie, chenhuan, xujie
# xujie, chenhuan, xujie, anyiji, 300
# xujie, chenhuan, xujie, anyiji, 300
- format_map不详,请指教
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 ""
- isidentifier不详
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
def join(self, iterable):
语法: ‘sep’.join(seq)
参数说明
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串
返回值:返回一个以分隔符sep连接各个元素后生成的字符串
参考:博客def lstrip(self, chars=None):去除字符串左侧空格
def rstrip(self, chars=None): 去除字符串右侧空格
def lower(self): 返回字符串的拷贝,并把所有字母都变成小写
def maketrans(self, *args, **kwargs):
Python maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
注:两个字符串的长度必须相同,为一一对应的关系。
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
str11 = "this is string example....wow!!!"
print(str11.translate(trantab))
# th3s 3s str3ng 2x1mpl2....w4w!!!
def partition(self, sep):
分割字符串,返回三元元组,第一个为分隔符左边,第二个为本身,第三个为右边def rpartition(self, sep):
print(str12.partition('d'))
print(str12.rpartition('d'))
print(str12.partition(','))
('abc', 'd', 'ed')
('abcde', 'd', '')
('abcded', '', '')
- def replace(self, old, new, count=None):
Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
str15 = "this is string example....wow!!! this is really string";
print(str15.replace("is", "was"))
print(str15.replace("is", "was", 3))
# thwas was string example....wow!!! thwas was really string
# thwas was string example....wow!!! thwas is really string
- def split(self, sep=None, maxsplit=-1):
- def rsplit(self, sep=None, maxsplit=-1):
seq为分割的字符(串),maxsplit为分割的次数 - def splitlines(self, keepends=None):
Python splitlines() 按照行(‘\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
keepends – 在输出结果里是否去掉换行符(‘\r’, ‘\r\n’, \n’),默认为 False,不包含换行符,如果为 True,则保留换行符。
str13 = 'a,b c,de fg'
print(str13.split())
print(str13.split(','))
print(str13.split(' ', 1))
print(str13.rsplit(' ', 1))
# ['a,b', 'c,de', 'fg']
# ['a', 'b c', 'de fg']
# ['a,b', 'c,de fg']
# ['a,b c,de', 'fg']