码迷,mamicode.com
首页 > 编程语言 > 详细

Python3字符串方法总结

时间:2017-06-12 20:39:31      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:ict   子串   failure   ons   tuple   返回   首字母   回车   field   

总算统计完了,他奶奶的,一定要努力啊!by 暗黑骑士

1、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 ""
View Code

描述:用于脱去字符串两边指定的字符(默认为空格)。

参数:chars  要脱去的子字符串

返回值:返回脱去子字符串后而生成的新字符串。

  • 示例1:
s = ‘    Hello World    ‘
print(‘原字符串>>>>‘,s,‘<<<<‘)
s1 = s.strip()
print(‘更改后的字符串>>>>‘,s1,‘<<<<<‘)

  输出结果:

技术分享
原字符串>>>>     Hello World     <<<<
更改后的字符串>>>> Hello World <<<<<
View Code  
  • 示例2:  
s = ‘*****Hello World*****‘
print(‘原字符串>>>>‘,s,‘<<<<‘)
s1 = s.strip(‘*‘)
print(‘更改后的字符串>>>>‘,s1,‘<<<<<‘) 

  输出结果:

技术分享
原字符串>>>> *****Hello World***** <<<<
更改后的字符串>>>> Hello World <<<<<
View Code

 

2、isspace()

  • 官方说明:
技术分享
    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
View Code

描述:检测字符串是否只由空格、tab、回车组成

参数:

返回值:返回布尔值

  • 示例1:
s = ‘      ‘
s1 = s.isspace()
print(type(s1),s1)

  输出结果:

技术分享
<class bool> True
View Code
  •  示例2:
s = ‘\t\n‘
s1 = s.isspace()
print(type(s1),s1)

  输出结果:

技术分享
<class bool> True
View Code

 

 

3、count()

  • 官方说明:
技术分享
    def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        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
View Code

描述:用于统计字符串里指定字符出现的次数。

参数:sub  查询的子字符串

     start 开始索引。默认为第一个字符,第一个字符索引值为0

     end  结束索引。字符中第一个字符 的索引为0。默认字符串的最后一个位置

返回值:返回整型,指定的字符在字符串中出现的次数。

  • 示例1:
s = ‘hello world‘
s1 = s.count(‘l‘)
print(type(s1),s1)

  输出结果:

技术分享
<class int> 3
View Code
  • 示例2:
s = ‘hello world‘
s1 = s.count(‘l‘,3,10) # 表示统计从索引位置3到9位置(顾首不顾尾)的子串的个数
print(type(s1),s1)

  输出结果:

技术分享
<class int>   2
View Code

 

4、split()

  • 官方说明:
技术分享
    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 []
View Code

描述:分隔字符串

参数:sep  分隔符

     maxsplit  最多分隔的次数

返回值:返回分割后的字符串列表

  • 示例1:
s = ‘hello world‘
s1 = s.split() # 括号内什么不加默认以空格为分隔符
print(type(s1),s1)# 得到一个列表

  输出结果:

技术分享
<class list> [hello, world]
View Code
  • 示例2:
s = ‘hello world‘
s1 = s.split(‘l‘) # 表示以字符"l"为分隔符
print(type(s1),s1)# 得到一个列表

  输出结果:

技术分享
<class list> [he, ‘‘, o wor, d]
View Code

 

5、replace()

  • 官方说明
技术分享
    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 ""
View Code

描述:子串替换

参数:old  要替换的字符串

     new  新的字符串

     count  替换次数

返回值:去掉字符串中的旧字符串,替换成新字符串后生成一个新的字符串。

  • 示例1:
s = ‘hello world‘
s1 = s.replace(‘world‘,‘python‘)
print(type(s1),s1)

  输出结果:

技术分享
<class str> hello python
View Code
  • 示例2:
s = ‘hello world world‘
s1 = s.replace(‘world‘,‘python‘,1)  # 只替换第一个world
print(type(s1),s1)

  输出结果:

技术分享
<class str> hello python world
View Code

 

6、index()

  • 官方说明:
技术分享
    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
View Code

描述:查找字符串,返回子串的索引,使用方法与find相同,不同之处是若查找的子串不存在会报错

参数:sub  查找的子字符串

     start  查找的起始位置

     end  查找的结束位置

返回值:若包含子字符串则返回开始的索引值,否则抛出异常。

  • 示例1:
s = ‘hello world‘
s1 = s.index(‘world‘) # 如果要查找的子字符串没有,则会抛出异常。
print(type(s1),s1)

  输出结果:

技术分享
<class int> 6
View Code
  • 示例2:
s = ‘hello world‘
s1 = s.index(‘o‘,5,10) # 表示从索引5至索引10的位置的开始查找字符“o“的所在的索引位置。
print(type(s1),s1)

  输出结果:

技术分享
<class int> 7
View Code

 

7、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 ""
View Code

描述:将字符串的首字母大写

参数:无

返回值:返回一个新的首字母大写的字符串对象。

  • 示例:
s = ‘hello world‘
s1 = s.capitalize()  # 将s字符串的首字母大字
print(type(s1),s1)

  输出结果:

技术分享
<class str> Hello world
View Code

8、center()

  • 官方说明 :
技术分享
    def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        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 ""
View Code

描述:让字符串居中对齐

参数:width  宽度,返回字符串长度

   fillchar  填充字符,不填默认以空格为填充字符

返回值:返回新的居中对齐的字符串

  • 示例1:
s = ‘hello world‘
s1 = s.center(26) # 字符串在26个空格中间
print(type(s1),‘起始位置‘,s1,‘结束位置‘)

  输出结果:

技术分享
<class str> 起始位置        hello world         结束位置
View Code
  • 示例2:
s = ‘hello world‘
s1 = s.center(26,‘#‘)  # 字符串在26个"#"号中间
print(type(s1),s1)

  输出结果:

技术分享
<class str> #######hello world########
View Code

 

9、encode()

  • 官方说明:
技术分享
    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""
View Code

描述:以指定的编码格式编码的字符串

参数:encoding  要使用的字符编码类型,如:UTF-8

   errors  设置不同错误的处理方案。默认为strict

返回值:返回指定编码的字节流(uncode编码)

  • 示例1:
s = ‘hello world‘
s1 = s.encode(‘ascii‘) # 将字符串编码成ascii格式的编码字符串
print(type(s1),s1)

  输出结果:

技术分享
<class bytes> bhello world
View Code
  • 示例2:
s = ‘世界你好‘
s1 = s.encode(‘utf-8‘)
print(type(s1),s1)

  输出结果:

技术分享
<class bytes> b\xe4\xb8\x96\xe7\x95\x8c\xe4\xbd\xa0\xe5\xa5\xbd
View Code
  •  示例3:
s = ‘世界你好‘
s1 = s.encode(‘gbk‘)
print(type(s1),s1)

  输出结果:

技术分享
<class bytes> b\xca\xc0\xbd\xe7\xc4\xe3\xba\xc3
View Code

 

10、endswith()

  • 官方说明:
技术分享
    def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        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
View Code

描述:判断是否以指定的子串结尾

参数:suffix  子串

   start  开始索引

   end  结束索引  

返回值: 返回布尔值

  • 示例1:
s = ‘hello world‘
s1 = s.endswith(‘rld‘)
print(type(s1),s1)

  输出结果:

技术分享
<class bool> True
View Code
  • 示例2:
s = ‘hello world‘
s1 = s.endswith(‘or‘,1,9) # 表示从索引位置1至8(顾首不顾尾)查找是否以字符‘or‘结尾
print(type(s1),s1)

  输出结果:

技术分享
<class bool> True
View Code

 

11、expandtabs()    

  • 官方说明:
技术分享
    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 ""
View Code

描述:把字符串中的\t符号转为空格。

参数:tabsize  指定字符串中\t转为空格的个数

返回值:返回字符串中\t转为空格后生成的新的字符串

  • 示例1:
s = ‘hello\tworld‘
print(len(s),s)
s1 = s.expandtabs()
print(type(s1),len(s1),s1)

  输出结果:

技术分享
11 hello    world
<class str> 13 hello   world
View Code
  • 示例2:
s = ‘x\tx\tx‘  # 原样式
print(len(s),s)
s1 = s.expandtabs(5)
print(type(s1),len(s1))
print(‘开始位置‘,s1,‘结束位置‘)

s2 = ‘x\txxxxxx\tx‘ # 前面的\t或中间\t的x个数只要大过了expandtabs括号中的参数,总长度就加上它的长度为准
print(len(s2),s2)
s3 = s2.expandtabs(5)
print(type(s3),len(s3))
print(‘开始位置‘,s3,‘结束位置‘)

s4 = ‘xxx\tx\txxxx‘# 字符串总长度是以最后一个\t后面字符串长度决定
print(len(s4),s4)
s5 = s4.expandtabs(5)
print(type(s5),len(s5))
print(‘开始位置‘,s3,‘结束位置‘)

  输出结果:

技术分享
5 x    x    x
<class str> 11
开始位置 x    x    x 结束位置
10 x    xxxxxx    x
<class str> 16
开始位置 x    xxxxxx    x 结束位置
10 xxx    x    xxxx
<class str> 14
开始位置 x    xxxxxx    x 结束位置
View Code

 

12、find()

  • 官方说明:
技术分享
    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
View Code

描述:检测字符串中是否包含指定的子串

参数:sub  要查找的子串

   start 查找的开始位置

   end  查找的结束位置

返回值:若包含子串则返回开始的索引值,否则返回-1

  • 示例1:
s = ‘hello world‘
s1 = s.find(‘l‘,5,10) # 查找索引5至9位置中的字符“l”的位置
print(type(s1),s1)

  输出结果:

技术分享
<class int> 9
View Code
  • 示例2:
s = ‘hello world‘
s1 = s.find(‘x‘) # 查找一个字符串中不存在的子串
print(type(s1),s1)

  输出结果:

技术分享
<class int> -1
View Code

 

13、format()

  • 官方说明:
技术分享
    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
View Code

描述:字符串的格式化输出。

种类:分别是%和{} 两种占位符格式控制符

数据格式类型:

(1)%%  百分号标记

(2) %c   字符及其ASCII码

(3) %s  字符串                重点

(4)%d  有符号整数(十进制)        重点

(5)%u  无符号整数(十进制)

(6)%o  无符号整数(八进制)

(7)%x  无符号整数(十六进制)

(8)%X  无符号整数(十六进制大写字符)

(9)%e  浮点数(科学计数法)

(10)%E  浮点数(科学计数法,用E代替e)

(11)%f  浮点数(用小数点符号)         重点

(12)%g  浮点数(根据值的大小采用%e或%f)

(13)%G  浮点数(类似于%g)

(14)%p  指针(用十六进制打印值的内存地址)

(15)%n  存储输出字符的数量放进参数列表的下一个变量中

参数:*args,**kwargs表示接收所有传参。

返回值:返回一个新的字符串。

  • 示例1:
s = ‘My name is {0},My age is {1}‘
s1 = s.format(‘William‘,18)
print(type(s1),s1)

# format会把传入的参数按位置顺序来填充,第一个参数是下标0,然后是1...一一对应

  输出结果:

技术分享
<class str> My name is William,My age is 18
View Code
  • 示例2:
s = "Hello, my name is {name},I‘m {age} year old,I am a {profession}"
s1 = s.format(profession=‘programmer‘,age=18,name=‘William‘)
print(type(s1),s1)

# format通过字典的key来填充,括号中可以不按顺序传参。

  输出结果:

技术分享
<class str> Hello, my name is William,Im 18 year old,I am a programmer
View Code
  • 示例3:
s = ‘my name is %s,my age is %d‘%(‘William‘,18)
print(type(s),s)

# 用%号进行字符串格式化

  输出结果:

技术分享
<class str> my name is William,my age is 18
View Code

 

14、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 ""
View Code

描述:

参数:

返回值:

示例:

15、isalnum()

  • 官方说明:
技术分享
    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
View Code

描述:判断一个字符串是否由字母和数字组成

参数:

返回值:返回一个布尔值(若字符串中有空格、\n、\t以及其它符号则返回返回False)

  • 示例:
s = ‘Alex是一个大SB88888888‘
s1 = s.isalnum()
print(type(s1),s1)

s2 = ‘helloworld8888\n‘
s3 = s2.isalnum()
print(type(s3),s3)

s4 = ‘hello\t world‘
s5 = s4.isalnum()
print(type(s5),s5)

  输出结果:

技术分享
<class bool> True
<class bool> False
<class bool> False
View Code

 

16、isalpha()

  • 官方说明:
技术分享
    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
View Code

描述:判断一个字符串是否全是字母

参数:

返回值:返回一个布尔值

  • 示例:
s = ‘88888hello world88888‘
s1 = s.isalpha()
print(type(s1),s1)

s2 = ‘helloworld‘
s3 = s2.isalpha()
print(type(s3),s3)

  输出结果:

技术分享
<class bool> False
<class bool> True
View Code

 

17、isdecimal()

  • 官方说明:
技术分享
    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
View Code

描述:判断字符串是否只包含十进制字符

参数:无

返回值:返回一个布尔值(包含十进制数则返回True,否则返回False)

  • 示例:
s = ‘88888888888888‘
s1 = s.isdecimal()
print(type(s1),s1)

  输出结果:

技术分享
<class bool> True
View Code

 

18、isdigit()

  • 官方说明:
技术分享
    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
View Code

描述:判断一个字符串中是否由数字组成

参数:

返回值:返回一个布尔值(如果由数字组成则返回True,否则返回False)

  • 示例:
s = ‘123456789‘
s1 = s.isdigit()
print(type(s1),s1)

  输出结果:

技术分享
<class bool> True
View Code

 

19、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
View Code

描述:是否是合法标识符

参数:无

返回值:返回一个布尔值

  • 示例:
s = ‘William888888‘
s1 = s.isidentifier()
print(type(s1),s1)

s2 = ‘hello world‘
s3 = s2.isidentifier()
print(type(s3),s3)

  输出结果:

技术分享
<class bool> True
<class bool> False
View Code

 

20、islower()

  • 官方说明:
技术分享
    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
View Code

描述:判断字符串是否全由写字母组成

参数:

返回值:返回一个布尔值(若字母都是小写则返回True,否则返回False)

  • 示例:
s = ‘William888888‘
s1 = s.islower()
print(type(s1),s1)

s2 = ‘88888hello world88888‘
s3 = s2.islower()
print(type(s3),s3)

  输出结果:

技术分享
<class bool> False
<class bool> True
View Code

 

21、isnumeric()

  • 官方说明:
技术分享
    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
View Code

描述:判断字符串是否只由数字组成。这种方法只针对unicode对象

参数:无

返回值:返回一个布尔值(如果字符串只包含数字字符,则返回True,否则返回False)

  • 示例:
s = ‘123456789‘
s1 = s.isnumeric()
print(type(s1),s1)

s2 = ‘88888hello world88888‘
s3 = s2.isnumeric()
print(type(s3),s3)

  输出结果:

技术分享
<class bool> True
<class bool> False
View Code

 

22、isprintable()

  • 官方说明:
技术分享
    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
View Code

描述:如果字符串中的所有字符都被认为是可打印的()或字符串是空的则返回True,否则返回False

参数:无

返回值:返回一个布尔值

  • 示例:
s = ‘\n\t\r‘
s1 = s.isprintable()
print(type(s1),s1)

s2 = ‘hello world‘
s3 = s2.isprintable()
print(type(s3),s3)

  输出结果:

技术分享
<class bool> False
<class bool> True
View Code

 

23、istitle()

  • 官方说明:
技术分享
    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
View Code

描述:判断字符串中的每个单词首字母是否为大写

参数:无

返回值:返回一个布尔值(字符串中的每个单词首字母为大写则返回True,否则返回False)

  • 示例:
s = ‘888888What Is Your Name?‘
s1 = s.istitle()
print(type(s1),s1)

s2 = ‘888888what is your name?‘
s3 = s2.istitle()
print(type(s3),s3)

  输出结果:

技术分享
<class bool> True
<class bool> False
View Code

 

24、isupper()

  • 官方说明:
技术分享
    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
View Code

描述:判断字符串是否全是大写

参数:

返回值:返回一个布尔值

  • 示例:
s = ‘88888MY NAME IS WILLIAM‘
s1 = s.isupper()
print(type(s1),s1)

s2 = ‘my name is William‘
s3 = s2.isupper()
print(type(s3),s3)

  输出结果:

技术分享
<class bool> True
<class bool> False
View Code

 

25、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 ""
View Code

描述:将序列中的元素以指定的字符连接,生成一个新的字符串。

参数:iterable  指定的字符

返回值:返回通过指定字符连接序列中元素后生成的新字符串

  • 示例:
s1 = ‘-‘
s2 = ‘‘
seq = (‘h‘,‘e‘,‘l‘,‘l‘,‘o‘)
print(s1.join(seq))
print(s2.join(seq))

  输出结果:

技术分享
h-e-l-l-o
hello
View Code

 

26、ljust()

  • 官方说明:
技术分享
    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 ""
View Code

描述:左对齐,右填充

参数:width  指定字符串长度。

   fillchar  填充字符,默认为空格。

返回值:返回一个原字符串右对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

  • 示例:
s = ‘hello world‘
s1 = s.ljust(50,‘*‘)
print(type(s1),s1)

  输出结果:

技术分享
<class str> hello world***************************************
View Code

 

27、lower()

  • 官方说明:
技术分享
    def lower(self): # real signature unknown; restored from __doc__
        """
        S.lower() -> str
        
        Return a copy of the string S converted to lowercase.
        """
        return ""
View Code

描述:将字符串中的大写字母替换成小写

参数:

返回值:返回一个小写的字符串

  • 示例:
s = ‘HELLO WORLD‘
s1 = s.lower()
print(type(s1),s1)

  输出结果:

技术分享
<class str> hello world
View Code

 

28、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 ""
View Code

描述:去掉字符串左边的空格或指定字符。

参数:chars  指定字符(默认是空格)

返回值:返回去掉字符串左边的指定的字符后生成的新字符串

  • 示例:
s = ‘        hello world         ‘
s1 = s.lstrip()
print(type(s1),‘开始位置‘,s1,‘结束位置‘)


s = ‘********hello world********‘
s1 = s.lstrip(‘*‘)
print(type(s1),‘开始位置‘,s1,‘结束位置‘)

  输出结果:

技术分享
<class str> 开始位置 hello world          结束位置
<class str> 开始位置 hello world******** 结束位置
View Code

 

29、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
View Code

描述:创建字符映射的转换表(两个字符串的长度必须相同,为一一对应的关系)

参数:*args

   **kwargs

返回值:

  • 示例:
s = ‘mnaei‘
s1 = ‘12345‘
rev = str.maketrans(s,s1)

str = ‘my name is william ‘
print(str.translate(rev))

  输出结果:

技术分享
1y 2314 5s w5ll531 
View Code

 

30、partition()

  • 官方说明:
技术分享
    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
View Code

描述:

参数:

返回值:

  • 示例:

 

31、rfind()

  • 官方说明:
技术分享
    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
View Code

描述:返回字符串最后一次出现的位置,如果没有匹配项则返回-1

参数:sub  查找的字符串

   start  开始查找的位置(默认为0)

   end  结束查找位置(默认为字符串的长度)

返回值:返回字符串最后一次出现的位置,如果没有匹配则返回-1

  • 示例:
s = ‘Alex is a big SB‘
s1 = ‘is‘
print(type(s.rfind(s1)),s.rfind(s1))

  输出结果:

技术分享
<class int> 5
View Code

 

32、rindex()

  • 官方说明:
技术分享
    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
View Code

描述:返回子串在字符串中最后出现的位置,如果没有匹配的字符串会报异常

参数:sub  查找的字符串

   start  开始位置

   end  结束位置

返回值:返回子串在字符串中最后出现的位置,如果没有匹配的字符串会报异常

  • 示例:
s = ‘Alex is a big SB‘
s1 = s.rindex(‘i‘)
print(type(s1),s1)

  输出结果:

技术分享
<class int> 11
View Code

 

33、rjust()

  • 官方说明:
技术分享
    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 ""
View Code  

描述:右对齐 ,或填充

参数:width  指定字符串长度。

   fillchar  填充字符,默认为空格。

返回值:返回一个原字符串右对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。

  • 示例:
s = ‘hello world‘
s1 = s.rjust(50,‘*‘)
print(type(s1),s1)

  输出结果:

技术分享
<class str> ***************************************hello world
View Code

 

34、rpartition()

  • 官方说明:
技术分享
    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
View Code

描述:从S的末尾开始,从S的末尾开始搜索分隔符,然后返回在它前面的部分,分隔符本身,以及后面的部分。如果没有找到分隔符,返回两个空字符串和s。

参数:sep  

返回值:返回在它前面的部分以及后面的部分。如果没有找到分隔符,返回两个空字符串和s。

  • 示例:
s = ‘Alex is a big SB‘
s1 = s.rpartition(‘ ‘)
print(type(s1),s1)

  输出结果:

技术分享
<class tuple> (Alex is a big,  , SB)
View Code

 

35、rsplit()

  • 官方说明:
技术分享
    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 []
View Code

描述:split是从左至右分隔字符串,而rsplit是从右至左分隔字符串

参数:sep  分隔符

     maxsplit  最多分隔的次数

返回值:返回分割后的字符串列表

  • 示例:
s = ‘hello world‘
s1 = s.rsplit(‘o‘,-1) 
print(type(s1),s1)

  输出结果:

技术分享
<class list> [hell,  w, rld]
View Code

 

36、rstrip()

  • 官方说明:
技术分享
    def rstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.rstrip([chars]) -> str
        
        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""
View Code

描述:删除字符串末尾指定的字符

参数:chars  指定删除的字符(默认为空格)

返回值:返回删除末尾指定的字符后生成的新字符串

  • 示例1:
s = ‘        hello world       ‘
print(len(s))
s1 = s.rstrip()
print(type(s1),len(s1),‘起始位置‘,s1,‘结束位置‘)

  输出结果:

技术分享
26
<class str> 19 起始位置         hello world 结束位置
View Code
  • 示例2:
s = ‘********hello world*********‘
print(len(s))
s1 = s.rstrip(‘*‘)   # 表示*作为分隔符
print(type(s1),len(s1),‘起始位置‘,s1,‘结束位置‘)

  输出结果:

技术分享
28
<class str> 19 起始位置 ********hello world 结束位置
View Code

 

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

描述:将字符串以\n,\r\n,\r为分隔符分隔成为一个列表。

参数:keepends  是一个布尔值。默认为False,改为True则显示保留\n、\r、\r\n这些分隔符

返回值:返回一个列表

  • 示例1:
s = ‘hello\r\nAlex is a big SB\nYes,he is‘
print(s)
s1 = s.splitlines()
print(type(s1),s1)

  输出结果:

技术分享
hello
Alex is a big SB
Yes,he is
<class list> [hello, Alex is a big SB, Yes,he is]
View Code
  • 示例2:
s = ‘hello\r\nAlex is a big SB\nYes,he is‘
print(s)
s1 = s.splitlines(True)
print(type(s1),s1)

  输出结果:

技术分享
hello
Alex is a big SB
Yes,he is
<class list> [hello\r\n, Alex is a big SB\n, Yes,he is]
View Code

 

38、startswith()

  • 官方说明:
技术分享
    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
View Code

描述:检测字符串是否以指定子串开头,如果是则返回True,否则返回False

参数:prefix  指定的子串

   start  开始的位置

   end  结束的位置

返回值:返回一个布尔值

  • 示例:
s = ‘hello world‘
s1 = s.startswith(‘llo‘,2,10)  # 表示从索引2位置至9的位置搜索是否有以字符“llo”开头的
print(type(s1),s1)

  输出结果:

技术分享
<class bool> True
View Code

 

39、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 ""
View Code

描述:字符串中的大小写互换

参数:无

返回值:返回一个字母大小写互换后的字符串

  • 示例:
s = ‘HELLO world‘
s1 = s.swapcase()
print(type(s1),s1)

  输出结果:

技术分享
<class str> hello WORLD
View Code

 

40、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 ""
View Code

描述:将字符串中的所有单词的第一个首字母大写

参数:无  

返回值:返回所有单词首字母大写后的字符串

  • 示例:
s = ‘my name is william‘
s1 = s.title()
print(type(s1),s1)

  输出结果:

技术分享
<class str> My Name Is William
View Code

 

41、translate()

技术分享
    def translate(self, table): # real signature unknown; restored from __doc__
        """
        S.translate(table) -> str
        
        Return a copy of the string S in which each character has been mapped
        through the given translation table. The table must implement
        lookup/indexing via __getitem__, for instance a dictionary or list,
        mapping Unicode ordinals to Unicode ordinals, strings, or None. If
        this operation raises LookupError, the character is left untouched.
        Characters mapped to None are deleted.
        """
        return ""
View Code

描述:使用上面的函数产后的翻译表,把S进行翻译,并把deletechars中有的字符删掉。

参数:

返回值:

示例:

42、upper()

  • 官方说明:
技术分享
    def upper(self): # real signature unknown; restored from __doc__
        """
        S.upper() -> str
        
        Return a copy of S converted to uppercase.
        """
        return ""
View Code

描述:将字符串中的小写字母转为大写字母

参数:

返回值:返回小写字母转为大写字母后的字符串

  • 示例:
s = ‘hello world‘
s1 = s.upper()
print(type(s1),s1)

  输出结果:

技术分享
<class str> HELLO WORLD
View Code

 

43、zfill()

  • 官方说明:
技术分享
    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 ""
View Code

描述:指定长度的字符串,在字符串的左侧填充"0"补齐

参数:width  指定字符串的长度。若超过原字符串长度则在前面填充0

返回值:返回指定长度的字符串

  • 示例:
s = ‘hello world‘
l = len(s)
print(l)
s1 = s.zfill(12)   # 指定的长度若超过字符串的长度则会在左侧打印0补齐
print(type(s1),s1)

  输出结果:

技术分享
11
<class str> 0hello world
View Code

 

Python3字符串方法总结

标签:ict   子串   failure   ons   tuple   返回   首字母   回车   field   

原文地址:http://www.cnblogs.com/fyknight/p/6963826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!