python str 方法

字符串的方法较多,字符串也是python中最为重要的一个数据类型

1:str --à转换为str 类型

classstr(object):
   
"""
    str(object='') -> str
    str(bytes_or_buffer[, encoding[,errors]]) -> str
   
    Create a new string object from thegiven object. If encoding or
    errors is specified, then the objectmust expose a data buffer
    that will be decoded using the givenencoding and error handler.
    Otherwise, returns the result ofobject.__str__() (if defined)
    or repr(object).
    encoding defaults tosys.getdefaultencoding().
    errors defaults to 'strict'.
    """

使用方法

a = 5
b = "test"
c = [1,2,3]
d = {'name':'好好学习','age':'天天向上'}

print("a:",type(str(a)))          ### 分别使用str 方法转换整型,列表,字典
print("b:",type(b))
print("c:",type(str(c)))
print("d:",type(str(d)))

###     输出结果
a: <class 'str'>
b: <class 'str'>
c: <class 'str'>
d: <class 'str'>

 

2:capitalize---à首字母转变成大写,如果首子母已经是大写则还是输出首字母大写结果

def capitalize(self): # real signature unknown; restored from __doc__
    """
    S.capitalize() -> str
    
    Return a capitalized version of S, i.e. make the first character
    have upper case and the rest lower case.
    """
    return ""

使用方法

a = 'hello world'
b = 'Test'

print("a:",a.capitalize())
print("b:",b.capitalize())

###             输出结果
a: Hello world
b: Test

 

3: casefold ---à大写转小写针对所有内容

def casefold(self): # real signature unknown; restored from __doc__
    """
    S.casefold() -> str
    
    Return a version of S suitable for caseless comparisons.
    """
    return ""

使用方法

a = 'hello World'
b = 'TEST'

print("a:",a.casefold())
print("b:",b.casefold())

###             输出结果
a: hello world
b: test

 

4:center ----à 内容居中

def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
    """内容居中:width :总长度 filcher :空白处添充内容,默认为空
    S.center(width[, fillchar]) -> str
    
    Return S centered in a string of length width. Padding is
    done using the specified fill character (default is a space)
    """
    return ""

使用方法

a= 'hello World'
b = 'TEST'

print("a:",a.center(20,'='))    ### 总长度:20 添充 '='
print("b:",b.center(20))         ### 总长度:20 默认添充空格

###             输出结果
a: ====hello World=====
b:         TEST

 

5:count ---à 统计出现的次数,返回一个正整数类型

def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
    """可选参数,sub :查询子序列的次数,start:起始位置;end 结束位置
    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.
    """
    return 0

使用方法

a = 'hello World'
b = 'TESTerscereastopooceweroqveitest,nowiertest,o celttest'

print("test_count:",b.count('test'))                ### 计算 test出现的次数
print("start_conut_end:",b.count('test',0,40))      ### 计算 0开始至40 test出现的次数

###             输出结果
test_count: 3
start_conut_end: 1

 

6:encode ---à 编码修改,unicode编码转换成其他编码的字符串,(转码的时候一定要先搞明白,字符串str是什么编码,然后decodeunicode,然后再encode成其他编码)

def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
    """ 默认转成utf-8,可选的提示错误信息为strict
    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""

使用方法:

test = '好好学习,天天向上'

print(test.encode)               ###  默认编码
print(test.encode('gb2312'))    ### gb2312

###  输出结果
<built-in method encode of str object at 0x02A4F448>
b'\xba\xc3\xba\xc3\xd1\xa7\xcf\xb0\xa3\xac\xcc\xec\xcc\xec\xcf\xf2\xc9\xcf'

 

7: endswith --à 判断是否以指定字符串结尾,返回bool值

def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
    """   ### 可选参数 start:起始位置,end :结束位置。
    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.
    """
    return False

使用方法:

a = 'hello World'
b = 'my name is zhang'

print("World:",a.endswith('World'))
print("World:",a.endswith('rld'))
print("World:",a.endswith('Wor'))
print("zhang_11_17:",b.endswith('zhang',11,17))
print("zhang_11_15:",b.endswith('zhang',11,15))

###             输出结果
World: True
World: True
World: False
zhang_11_17: True
zhang_11_15: False

 

8: expandtabs -à 将字符串中的tab(\t)转换为空格,默认空格数tabsize 是8个字符

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 ""
a = 'hello\tWorld'
b = 'my\tname\tis\tzhang'

print(a)
print('a_expandtabs:',a.expandtabs())
print('a_expandtabs:',a.expandtabs(20))        ###  设备为20个字符间隔
print('b_expandtabs:',b.expandtabs())


###             输出结果
hello  World
a_expandtabs: hello   World
a_expandtabs: hello               World
b_expandtabs: my      name    is      zhang

 

9:find -à 查找字符串所在的位置,可先参数start:起始位置,end:结束位置。结果将返回int类型。如果查找失败返回-1

def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
    """
    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.
    """
    return 0

使用方法:

a = 'hello World'
#b = 'my name is zhang'

print('ll:',a.find('ll'))
print('ll_1_5:',a.find('ll',1,5))       ### 1-5 的位置查找
print('ll_5_10:',a.find('ll',5,10))     ### 5-10 的位置查找,不存在返回-1

###             输出结果
ll: 2
ll_1_5: 2
ll_5_10: -1

 

10:format ---à 字符串格式化(可接收不限数量参数,使用‘{}’占位符)

def format(*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

使用方法

print('{0},I\'m {1},my mail is {2}'.format('Hello','zhang','test@gmail.com'))

#######  输出结果
Hello,I'm zhang,my mail is test@gmail.com

 

11: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 ""

 

12:index --à 返回索引位置;可先参数,start:起始位置,end:结束位置,返回一个整数类型(当字符串没有找到时,会提示报错信息)

def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
    """
    S.index(sub[, start[, end]]) -> int
    
    Like S.find() but raise ValueError when the substring is not found.
    """
    return 0

方法

a = 'hello World'
#b = 'my name is zhang'

print('Wo_index :',a.index('Wo'))
print('Wo_index_3,10:',a.index('Wo',3,10))
print('Wo_index_3,5:',a.index('Wo',3,5))

###  输出结果
Wo_index : 6
  File "C:/Users/zhang/PycharmProjects/S12/day3/test_float.py", line 40, in <module>
Wo_index_3,10: 6
    print('Wo_index_3,5:',a.index('Wo',3,5))
ValueError: substring not found                    ###  未找到,报错

 

13:isalnum --- > 字符串都是字符,数字 或是字符数字组合则为True否则为False

def isalnum(self): # real signature unknown; restored from __doc__
    """
    S.isalnum() -> bool
    
    Return True if all characters in S are alphanumeric
    and there is at least one character in S, False otherwise.
    """
    return False

使用方法:

a = '30'
b = '天天向上'
c = 'name:zhang'
d = 'this is test'
e = 'thisistest'

print("a:",a.isalnum())
print("b:",b.isalnum())
print("c:",c.isalnum())
print("d:",d.isalnum())
print("e:",e.isalnum())

###    输出结果
a: True
b: True
c: False
d: False
e: True

 

14:isalpha -à  字符串中有一个为字母或所有都是字母都 True 否则为False

def isalpha(self): # real signature unknown; restored from __doc__
    """
    S.isalpha() -> bool
    
    Return True if all characters in S are alphabetic
    and there is at least one character in S, False otherwise.
    """
    return False

使用方法:

a = '30'
b = '天天向上'
c = 'name:zhang'
d = 'this is test'
e = 'thisistest'

print("a:",a.isalpha())
print("b:",b.isalpha())
print("c:",c.isalpha())
print("d:",d.isalpha())
print("e:",e.isalpha())

###    输出结果
a: False
b: True
c: False
d: False
e: True

 

15: isdecimal -à 如果只有十进制则返回True,否则返回False

def isdecimal(self): # real signature unknown; restored from __doc__
    """
    S.isdecimal() -> bool
    
    Return True if there are only decimal characters in S,
    False otherwise.
    """
    return False

使用方法:

a = '30'
b = '天天向上'
c = 'name:zhang'
d = 'this is test'
e = 'thisistest'

print("a:",a.isdecimal())
print("b:",b.isdecimal())
print("c:",c.isdecimal())
print("d:",d.isdecimal())
print("e:",e.isdecimal())

###    输出结果
a: True
b: False
c: False
d: False
e: False

 

16: isdigit -à 元素全部为数字时返回 True否则返回 False

def isdigit(self): # real signature unknown; restored from __doc__
    """
    S.isdigit() -> bool
    
    Return True if all characters in S are digits
    and there is at least one character in S, False otherwise.
    """
    return False

使用方法:

a = '30'
b = '天天向上2016'
c = 'name:zhang'
d = 'this is test'
e = 'thisistest'

print("a:",a.isdigit())
print("b:",b.isdigit())
print("c:",c.isdigit())
print("d:",d.isdigit())
print("e:",e.isdigit())

###    输出结果
a: True
b: False
c: False
d: False
e: False

 

17: isidentifier --à 判断字符串是否是合法的标识符(标识符必须合法)返回bool类型

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

使用方法:

a = '5'
b = '天天向上2016'               ###  合法标识符
c = 'name:zhang'                 ### 不合法
d = 'this is test'               ### 不合法
e = 'thisistest'                 ### 法标识符

print("a:",a.isidentifier())
print("b:",b.isidentifier())
print("c:",c.isidentifier())
print("d:",d.isidentifier())
print("e:",e.isidentifier())

###    输出结果
a: False
b: True
c: False
d: False
e: True

 

18: islower --à 判断是不是小写,返回bool值

def islower(self): # real signature unknown; restored from __doc__
    """
    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.
    """
    return False

使用方法:

a = '5'
b = '天天向上2016'               ###  中文件+数字
c = 'name:zhang'                 ### 全部小写
d = 'this is test'               ### 全部小写
e = 'Thisistest'                 ### 首字母大写

print("a:",a.islower())
print("b:",b.islower())
print("c:",c.islower())
print("d:",d.islower())
print("e:",e.islower())

###    输出结果
a: False
b: False
c: True
d: True
e: False

 

19: isupper --à 判断是不是都是大写,返回bool值

def isupper(self): # real signature unknown; restored from __doc__
    """
    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.
    """
    return False

使用方法:

a = '5'
b = '天天向上2016'               ###  中文件+数字
c = 'NAME:ZHANG'                 ### 全部大写
d = 'this is test'               ### 全部小写
e = 'ThISISTEST'                 ### 全部大写

print("a:",a.islower())
print("b:",b.islower())
print("c:",c.islower())
print("d:",d.islower())
print("e:",e.islower())

###    输出结果
a: False
b: False
c: False
d: True
e: False

 

这里发现一个问题:就是c 的值,全部小写时被islower返回True,全部大写时确被isupper返回False

 

20: isnumeric ---à 判断是不是全部为数字,返回Bool值

def isnumeric(self): # real signature unknown; restored from __doc__
    """
    S.isnumeric() -> bool
    
    Return True if there are only numeric characters in S,
    False otherwise.
    """
    return False

使用方法

a = '5'
b = '天天向上2016'               
c = 'NAME:ZHANG'                 
d = 'this is test'               
e = 'ThISISTEST'                 

print("a:",a.isnumeric())
print("b:",b.isnumeric())
print("c:",c.isnumeric())
print("d:",d.isnumeric())
print("e:",e.isnumeric())

###    输出结果
a: True
b: False
c: False
d: False

 

21:isprintable --à 判断是不是只包含可打印字符,返回Bool值

def isprintable(self): # real signature unknown; restored from __doc__
    """
    S.isprintable() -> bool
    
    Return True if all characters in S are considered
    printable in repr() or S is empty, False otherwise.
    """
    return False

使用方法:

a = '5'
b = '天天向上\t2016'
c = 'NAME:ZHANG'
d = 'this is test'
e = 'ThISISTEST'

print("a:",a.isprintable())
print("b:",b.isprintable())
print("c:",c.isprintable())
print("d:",d.isprintable())
print("e:",e.isprintable())

###    输出结果
a: True
b: False
c: True
d: True
e: True

 

22: isspace -à 判断是不是只包含空格字符,返回bool值

def isspace(self): # real signature unknown; restored from __doc__
    """
    S.isspace() -> bool
    
    Return True if all characters in S are whitespace
    and there is at least one character in S, False otherwise.
    """
    return False

使用方法:

a = '5'
b = '天天向上\t2016'
c = 'NAME:ZHANG'
d = ' '
e = 'ThISISTEST'

print("a:",a.isspace())
print("b:",b.isspace())
print("c:",c.isspace())
print("d:",d.isspace())
print("e:",e.isspace())

###    输出结果
a: False
b: False
c: False
d: True
e: False

 

23: istitle -à 判断是不是每个词的首字母是不是大写,返回Bool值

def istitle(self): # real signature unknown; restored from __doc__
    """
    S.istitle() -> bool
    
    Return True if S is a titlecased string and there is at least one
    character in S, i.e. upper- and titlecase characters may only
    follow uncased characters and lowercase characters only cased ones.
    Return False otherwise.
    """
    return False

返回结果

a = '5'
b = '天天向上\t2016'
c = 'NAME:ZHANG'
d = 'This Is Test'
e = 'ThISISTEST'

print("a:",a.istitle())
print("b:",b.istitle())
print("c:",c.istitle())
print("d:",d.istitle())
print("e:",e.istitle())

###    输出结果
a: False
b: False
c: False
d: True
e: False

 

24:join -à 返回通过指定字符分隔的新字符串

def join(self, iterable): # real signature unknown; restored from __doc__
    """
    S.join(iterable) -> str
    
    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.
    """
    return ""

使用方法

test= 'my name is zhang'
test1 = ('my','name','is','zhang')
print('-'.join(test))
print('-'.join(test1))

### 输出结果
m-y- -n-a-m-e- -i-s- -z-h-a-n-g
my-name-is-zhang

 

25:ljust --à 左对齐,右添充,参数width 宽度(fillchar 添充字符,默认是空格)

def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
    """
    S.ljust(width[, fillchar]) -> str
    
    Return S left-justified in a Unicode string of length width. Padding is
    done using the specified fill character (default is a space).
    """
    return ""

使用方法:

test= 'my name is zhang'
print(test.ljust(20))
print(test.ljust(20,'='))

### 输出结果
my name is zhang    
my name is zhang====

 

26: lower -à 转换为小写(这里不再做示例)

def lower(self): # real signature unknown; restored from __doc__
    """
    S.lower() -> str
    
    Return a copy of the string S converted to lowercase.
    """
    return ""

 

27:lstrip -à 删除左边的空白或自定义的字符

def lstrip(self, chars=None): # real signature unknown; restored from __doc__
    """
    S.lstrip([chars]) -> str
    
    Return a copy of the string S with leading whitespace removed.
    If chars is given and not None, remove characters in chars instead.
    """
    return ""

使用方法:

test= '   my name is zhang'
print(test.lstrip())
print(test.lstrip(' '))             ### 删除左边的空格

### 输出结果
my name is zhang
my name is zhang

 

28: maketrans -à 此方法有待考究

def maketrans(self, *args, **kwargs): # real signature unknown
    """
    Return a translation table usable for str.translate().
    
    If there is only one argument, it must be a dictionary mapping Unicode
    ordinals (integers) or characters to Unicode ordinals, strings or None.
    Character keys will be then converted to ordinals.
    If there are two arguments, they must be strings of equal length, and
    in the resulting dictionary, each character in x will be mapped to the
    character at the same position in y. If there is a third argument, it
    must be a string, whose characters will be mapped to None in the result.
    """
    pass

 

29:partition -à 用于拆分字符串,返回一个包含三个元素的元组;返回一个包含三个元素的元组。如果指定的字符串sep不存在,则返回自己加两个空元素。

def partition(self, sep): # real signature unknown; restored from __doc__
    """
    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

使用方法:

test= '   my name is zhang'
print(test.partition('y'))
print(test.partition('is'))
print(test.partition('zz'))

### 输出结果
('   m', 'y', ' name is zhang')
('   my name ', 'is', ' zhang')
('   my name is zhang', '', '')

 

30:replace --à 使用新的字符串替换老的字符串(可选参数count 指定替换的次数,默认是全部)

def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
    """ 
    S.replace(old, new[, count]) -> str
    
    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 ""

使用方法:

test= '   my name is zhang,my name is lisi'
print(test.replace('name','age'))
print(test.replace('name','age',1))              ###  替换一次
print('AABBCCDDAA'.replace('AA','FF'))

### 输出结果
   my age is zhang,my age is lisi
   my age is zhang,my name is lisi
FFBBCCDDFF

 

31: rfind --à 反向查找,与find 是相反方向,这里不再细说

def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
    """
    S.rfind(sub[, start[, end]]) -> int
    
    Return the highest 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.
    """
    return 0

 

32:rindex --à 返回字符串所在的索引,与index 相反方向

def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
    """
    S.rindex(sub[, start[, end]]) -> int
    
    Like S.rfind() but raise ValueError when the substring is not found.
    """
    return 0

 

33:rjust -à 右对齐,右填充。与ljur 相反

def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
    """
    S.rjust(width[, fillchar]) -> str
    
    Return S right-justified in a string of length width. Padding is
    done using the specified fill character (default is a space).
    """
    return ""

 

34:rpartition --à 拆分:与 partition相反,只不过是从字符串的右边开始拆分。

def rpartition(self, sep): # real signature unknown; restored from __doc__
    """
    S.rpartition(sep) -> (head, sep, tail)
    
    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

 

35:rsplit -à 与split类似,从右边开始拆分,返回一个列表类型,(可选参数maxsplit 每次+- 1  sep 的值默认是空格)

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 []

使用方法:

test = 'my name is zhang,my name is lisi'
test1= 'ababcd ababcd'

print(test.rsplit('name'))
print(test1.rsplit('b'))
print(test1.rsplit('b',2))     

### 输出结果
['my ', ' is zhang,my ', ' is lisi']
['a', 'a', 'cd a', 'a', 'cd']
['ababcd a', 'a', 'cd']

 

36:split -à 与rsplit 相反,从左边开始操作,这里不做操作演示

def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
    """
    S.split(sep=None, maxsplit=-1) -> list of strings
    
    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 []

 

37:splitlines -à 拆分多行字符串,以每行一个元素生成一个新的列表,如果是单行字符串,则返回原字符串。

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 []

使用方法:

test = 'my name is zhang,my name is lisi'
test1= 'ababcd  \
        ababcd'

print(test.splitlines())
print(test1.splitlines())

### 输出结果
['my name is zhang,my name is lisi']
['ababcd          ababcd']

 

38: startswith -à 是否以字符串开始(可选参数,start与end 分别代表起始和结束),返回bool值

def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
    """
    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.
    """
    return False

使用方法:

test = 'my name is zhang,my name is lisi'
test1= 'ababcd  \
        ababcd'

print(test.startswith('my'))
print(test.startswith('name'))

### 输出结果
True
False

 

39:strip -à 去除左边空白或自定义字符串

def strip(self, chars=None): # real signature unknown; restored from __doc__
    """
    S.strip([chars]) -> str
    
    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 ""

使用方法

test = '  my name is zhang,my name is lisi'
test1= 'ababcd  \
        ababcd'

print(test.strip())
print(test.strip('is'))               ### 这个结果很奇怪

### 输出结果
my name is zhang,my name is lisi
  my name is zhang,my name is l

 

40:swapcase -à 把字符串的大小写字母互换输出

def swapcase(self): # real signature unknown; restored from __doc__
    """
    S.swapcase() -> str
    
    Return a copy of S with uppercase characters converted to lowercase
    and vice versa.
    """
    return ""

使用方法:

test = '  my name IS zhang,my NAME is lisi'
test1 = 'ababcd  \
        ababcd'

print(test.swapcase())

### 输出结果
  MY NAME is ZHANG,MY name IS LISI

 

41: title -à 字符串首字母大写,其他全部小写

def title(self): # real signature unknown; restored from __doc__
    """
    S.title() -> str
    
    Return a titlecased version of S, i.e. words start with title case
    characters, all remaining cased characters have lower case.
    """
    return ""

使用方法:

a= '5'
b = '天天向上\t2016'
c = 'NAME:ZHANG'
d = 'This Is Test'
e = 'ThISISTEST'

print(a.title())
print(b.title())
print(c.title())
print(d.title())
print(e.title())

### 输出结果
5
天天向上   2016
Name:Zhang
This Is Test
Thisistest

 

42: translate -à str.maketrans()函数配合使用,替换相应的字符

def translate(self, table): # real signature unknown; restored from __doc__
    """
    S.translate(table) -> str
    
    Return a copy of the string S, where all characters have been mapped
    through the given translation table, which must be a mapping of
    Unicode ordinals to Unicode ordinals, strings, or None.
    Unmapped characters are left untouched. Characters mapped to None
    are deleted.
    """
    return ""

 

43:upper -à 与lower 相反,全部转换为大写

def upper(self): # real signature unknown; restored from __doc__
    """
    S.upper() -> str
    
    Return a copy of S converted to uppercase.
    """
    return ""

 

44:zfill-à 返回一个添充的字符串,width 添写长度,如果长宽和字符串相等,则直接返回字符串本身,如果长度大小字符串,则用0添充至指定的长度

def zfill(self, width): # real signature unknown; restored from __doc__
    """
    S.zfill(width) -> str
    
    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 ""

使用方法:

d= 'This Is Test'
e = 'ThISISTEST'

print(d.zfill(10))
print(d.zfill(50))
print(e.zfill(50))
### 输出结果
This Is Test
00000000000000000000000000000000000000This Is Test
0000000000000000000000000000000000000000ThISISTEST

 

 字符串的格式化输出对我们来说非常有用

例子:

print('my name is %s' % 'zhang')
print('my ageis %d'% 25)
print('yourheight is %f ?' % (1.75))
test
= """
    name:%s
    age:%d
    job:%s
"""
print(test %('zhang',25,'IT'))
### 输出结果
my name is zhang
my age
is 25
your height is 1.750000?

    name
:zhang
    age
:25
   
job:IT


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值