描述

encode(卡塔尔(قطر‎方法以内定的编码格式编码字符串。errors参数能够钦点分歧的错误管理方案。

str字符串常用方法,str字符串

描述

find(卡塔尔国 方法检查评定字符串中是还是不是包罗子字符串 str ,如若钦点 beg(开端) 和
end(甘休)
范围,则检查是还是不是含有在钦定范围内,固然钦命范围内假如含有钦命索引值,重返的是索引值在字符串中的最早地方。若是不蕴含索引值,重回-1。

Python字符串str的不二秘技运用,python字符串str

#!usr/bin/env python
# -*-coding:utf-8-*-
#字符串通常用双引号或单引号来表示:'123',"abc","字符串"
#str字符串的常用方法有以下:字符串可以用于赋值临时变量s
#友情提示以下全是python2.x版本演示,python3.x请在print(放入测试打印),例如:print(len(s))
from string import maketrans
s3 = '123'
s2 = '   '
s1 = 'This Is \t Cash'
s='abcdefghijklmnopqrstuvwxyz'
s4 = "0000000this is string example....wow!!!0000000"
s5 = 'ab c\n\nde fg\rkl\r\n'
print s[0:6]    #切片,截取字符串中的一段(以下标的起始位置到结束位置)
print len(s)    #统计字符串的长度
print s.ljust(50,'0'),'--->ljust方法'   #返回一个原字符串右用字符串0填充左对齐并宽度50的新字符串
print s.rjust(50,'0'),'--->rjust方法'   #返回一个原字符串左用字符串0填充右对齐并宽度50的新字符串
print s.capitalize(),'--->capitalize方法'    #返回字符串首字母大写的副本
print s.center(50,'*'),'--->center方法'  #表示原字符串居中两边填充宽度的用法
print format(s, '.3'),'--->format方法'   #格式化输出也可当切片用的方式
print s.upper(),'--->upper方法' #将小写字母转换成大写字母
print s.lower(),'--->lower方法' #将大写字母转换成小写字母
print s3.isdigit(),'--->isdigit方法'   #判断字符串如果是数字返回真True,不是返回假False
print s.startswith('abc'),'--->startswith方法'   #判断字符串是否是以abc开头如果是返回真,否则返回假
print s.endswith('zz'),'--->endswith方法'  #判断字符串是否以yz结尾是返回真,否则返回假
print s1.expandtabs(),'--->expandtabs方法'   #把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是8
print s.isalnum(),'--->isalnum方法'   #判断字符串至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
print s.isalpha(),'--->isalpha方法'   #判断字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False
print s2.isspace(),'--->isspace方法'  #判断字符串中只包含空格,则返回 True,否则返回 False
print s1.istitle(),'--->istitle方法'   #如果字符串中所有的单词拼写首字母是否为大写,且其他字母为小写则返回 True,否则返回 False
print s4.strip("0"),'--->strip方法' #返回移除字符串头尾指定的字符生成的新字符串
print s.find('sd'),'--->find方法'   #检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
print s.index('s'),'--->index方法'  #检查是否包含在指定范围内,该方法与find()方法一样,只不过如果不在字符串中会报一个异常
print s.partition("k"),'--->partition方法'  #生成一个分隔符k,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。
print s1.swapcase(),'--->swapcase方法' #返回大小写字母转换后生成的新字符串
print s5.splitlines(),'--->splitlines方法'   #返回一个包含各行作为元素的列表
print s2.join(s3),'--->join方法'   #返回通过指定字符连接序列中元素后生成的新字符串
print s3.translate(maketrans(s3,s2)) #返回翻译后的字符串(有点复杂)自信百度补脑
print s3.zfill(10),'--->zfill方法'  #返回指定宽度的字符串原字符串右对齐,前面填充0
#以下打印输出:

图片 1

#!usr/bin/env python # -*-coding:utf-8-*-
#字符串平常用双引号或单引号来代表:’123′,”abc”,”字符串”
#str字符串…

字符串常量方法的主宰以致decode和encode的熟稔驾驭,str和unicode的分别使用

  • 字符串常量的不二秘技

# 列表反序   [::-1] 内置函数reversed
In [83]: s = "hello world"
In [84]: s[::-1]
Out[84]: 'dlrow olleh'
In [87]: "".join(reversed(s))
Out[87]: 'dlrow olleh'

# 索引和分片
str = "abcdefg"
print(str)--->打印全部
print(str[0])--->打印第一个值a
print(str[0:-1])--->打印全部
print(str[2:4])--->打印cd--[m,n]/表示的是从下标m到n-1
print(str[2:])--->从下标2到最后
print(str*2)--->打印全部数据两次
# 经常用到的是字符串和整数之间的转换
eg: str="2" b=int(str)-->b=2是一个整数类型
print(str[::-1])--->字符串反转
print(str[::2])--->每间隔两个下标取一个值

# 字符串大小写相关的方法
In [93]: x = "abcdefg"
In [94]: len(x)             # 获取字符串的长度
Out[94]: 7
In [95]: x.upper()          # 将字符串转换为大写
Out[95]: 'ABCDEFG'
In [96]: x.lower()          # 将字符串转换为小写
Out[96]: 'abcdefg'
In [97]: x1 = "heLLo wORld"
In [98]: x1.isupper()       # 判断字符串是否都是大写
Out[98]: False
In [99]: x1.islower()       # 判断字符串是否都是小写
Out[99]: False
In [100]: x1.swapcase()     # 将字符串中的字母大写转小写,小写转大写
Out[100]: 'HEllO WorLD'
In [101]: x.capitalize()    # 将字符串中的首字母转为大写
Out[101]: 'Abcdefg'

# 判断类 startswith endswith--->判断字符串是否是以什么开头结尾的
In [103]: x1.startswith("index")
Out[103]: False
In [104]: x1
Out[104]: 'heLLo wORld'
In [105]: x1.startswith("he")
Out[105]: True

# 查找类函数
find --->查找字串在字符串中的位置,查找失败返回-1
index--->和find相似,查找失败报错ValueError;index-->在字符串中查找字串第一次出现的位置,返回下标;
rfind -->与find类似,区别在于从后面开始查找
In [106]: s = 'Return the lower index in S where substring sub is found'
In [107]: s.find("in")
Out[107]: 17
In [108]: s.find("hh")
Out[108]: -1
In [109]: s.rfind("is")
Out[109]: 48
In [110]: s.find("is",20)       # 指定从哪个下标开始查找
Out[110]: 48
In [111]: s.index("the")
Out[111]: 7

# 拆分 去重复
字符串中strip用法--->只移除字符串头尾指定的字符,中间的部分不会移除
str = "0000000this is string 0000example....wow!!!0000000"
print str.strip('0')
结果:this is string 0000example....wow!!!
字符串中lstrip()--->用于截掉字符串左边的空格或指定字符
字符串中rstrip()--->用于截掉字符串右边的空格或指定字符

字符串中split的用法--->用于分割某个字符串/得到一个分割后的列表
str = "abcdefg"
str.split("c")
结果:['ab', 'defg']

# 字符串格式化format
1、占位符或者下标形式显示
In [114]: "{} is apple".format("apple")
Out[114]: 'apple is apple'
In [115]: "{0} is apple".format("apple")
Out[115]: 'apple is apple'
2、关键字参数形式访问
In [116]: dic = {"a":1,"b":2,"c":3}
In [118]: "{a} is 1, {b} is 2,{c} is 3,{a} little {c}".format(**dic)
Out[118]: '1 is 1, 2 is 2,3 is 3,1 little 3'
3、format的其他功能
In [120]: "{:.2f}".format(3.1415926)        # 保留两位小数
Out[120]: '3.14'
In [121]: "{:10.2f}".format(3.1415926)      # 前面补十个空格
Out[121]: '      3.14'
In [122]: "{:^10.2f}".format(3.1415926)     # ^两端对齐
Out[122]: '   3.14   '
In [124]: "{:_^10.2f}".format(3.1415926)    # _空格补位
Out[124]: '___3.14___'
  • decode 和 encode

    • decode–>解码、encode–>编码
    • 首先要搞领会,字符串在python内部的表示是unicode编码;因而在做编码转的时,常常供给以unicode作为中间编码,即先将其它编码的字符串解码(decode卡塔尔成unicode,再从unicode编码(encode卡塔尔(قطر‎成另黄金年代种编码;
      • decode的效劳是将其余编码的字符串转变来unicode编码,如str1.decode(“gbk2312″卡塔尔(英语:State of Qatar),表示将gbk2312编码的字符串str1调换来unicode编码
      • encode的魔法是将unicode编码转变来其余编码的字符串,如str2.encode(“gb2312″卡塔尔,表示将unicode编码的字符串str2调换到gb2312编码
    • 总的意思是:想要将此外的编码转变来utf-8必得先将其解码成unicode然后再行编码成utf-8,它是以unicode为转移媒介的

    In [150]: ss = "中文"
    In [151]: l = ss.decode("utf-8")                # 将utf8解码成unicode
    In [152]: isinstance(l,unicode)                 
    Out[152]: True
    In [153]: l = l.encode("utf-8")                 # 将unicode编码成utf8
    In [154]: isinstance(l,unicode)
    Out[154]: False
    In [155]: import sys
    In [156]: print sys.getdefaultencoding()        # Linux系统下默认的是ascii
    ascii
    
    # 修改系统默认编码
    In [167]: print sys.getdefaultencoding()        # 获取系统默认编码
    ascii
    In [168]: reload(sys)
    <module 'sys' (built-in)>
    In [169]: sys.setdefaultencoding("utf8")        # 修改系统默认编码
    In [170]: print sys.getdefaultencoding()
    utf8
    
  • str和unicode的差别使用

    • 先是知道概念:str->decode(“coding”卡塔尔国->unicode->encode(“coding”卡塔尔国->str
    • str和unicode都以basestring下边包车型地铁子类
    • 分别:str是字符串,是unicode编码(encode卡塔尔后的字节组成的
    • 多个华语字符串在unicode中占一个字节,在gbk中占2个字节,在utf-第88中学占3个字节
      • win系统默许编码是gbk,Linux暗中同意编码是utf-8,py文件暗中认可编码是ascii
    • py文件默许的是ascii,如若用到非ascii字符,须求在文书的底部举行编码表明
      • # -*- coding: utf-8 -*- 或者#coding=utf-8
      • 若底部证明coding=utf-8, a = ‘粤语’其编码为utf-8
      • 若底部宣称coding=gb2312, a = ‘中文’ 其编码为gbk
    • 暗许使用法规
      • 不对str使用编码(encode卡塔尔国,不对unicode使用解码(decode卡塔尔(قطر‎

    In [8]: a = "中文"
    In [14]: u = a.decode("utf-8")
    In [15]: type(u)
    Out[15]: unicode
    In [16]: u = u.encode("utf-8")
    In [17]: type(u)
    Out[17]: str
    In [18]: len(u)
    Out[18]: 6
    

语法

encode(卡塔尔(英语:State of Qatar)方英文法:

str.encode(encoding='UTF-8',errors='strict')

    字符串是编制程序中常用的花色,字符型在内部存款和储蓄器中是以单个形式累积的,举例name

“alex”,在内部存款和储蓄器中储存的样式为[“a”,”l”,”e”,”x”],由此大家得以应用列表的过多意义来操作字符串,因为笔者起来的时候向来在想干什么字符串能够运用切条,能够有目录,最早的时候一向不领悟,后来清楚了Python字符串的寄存方式之后才清楚为何存在这里些主意。上边咱们来拜谒字符串类型中包罗这一个方法:

   
在Python中稍稍措施上面有注释,这是因为这几个措施运用Python自身编辑的,大家明白Python中大多是直接调用C语言中的方法,看不到的那么些是C语言中的方法。

    1.capitalize(self)

    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 “”

   
capitalize(self卡塔尔是居首首字母大写,大家领略还会有四个主意title(卡塔尔(英语:State of Qatar),上边来相比较那四个措施的区别点:

    >>> name = “alex is sb”
  >>> name.capitalize()
  ’Alex is sb’
  >>> name.title()
  ’Alex Is Sb’

   
从上边能够观看,capitalize(self卡塔尔(قطر‎是位居第3位首字母大写,别的字母一点都不大写;而title(self卡塔尔国方法是两全单词的首字母都大写,那个在用的时候要知道是要求那么字母大写。

    2.casefold(self)

    def casefold(self): # real signature unknown; restored from
__doc__
    ”””
    S.casefold() -> str
        全体首字母小写,等价于lower(卡塔尔(قطر‎
    Return a version of S suitable for caseless comparisons.
    ”””
    return “”

    casefold(self卡塔尔国是将大写字母转化为小写,等价于lower(self卡塔尔(قطر‎,实举个例子下:

    >>> name = “ALEX Is SB”
  >>> name.casefold()
  ’alex is sb’
  >>> name
  ’ALEX Is SB’
  >>> name.lower()
  ’alex is sb’

  3.center(self,width,fillchar=None)

    def center(self, width, fillchar=None): # real signature unknown;
restored from __doc__
    ”””
    S.center(width[, fillchar]) -> str
       
“””center(self,width,fillchar=None卡塔尔是将字符串放到中间,两边加上任意符号,暗中同意空格”””
    Return S centered in a string of length width. Padding is
    done using the specified fill character (default is a space)
    ”””
    return “”

   
center(self,width,fillchar=None卡塔尔国,美化格式,把self放到中间,钦赐自便长度的字符,空白处用字符填充,私下认可时间和空间字符。示比如下:

    >>> name = “您好”
  >>> name.center(12)
  ’     您好     ‘
  >>> name.center(12,”-“)
  ’—–您好—–‘

    4.__format__(self,format_spec)

    def __format__(self, format_spec): # real signature unknown;
restored from __doc__
    ”””
    S.__format__(format_spec) -> str
        字符串的格式化
    Return a formatted version of S as described by format_spec.
    ”””
    return “”

   
__format__(self,format_spec卡塔尔字符串举行格式化,根据我们渴求的格式进行字符串格式化操作。详细可参照他事他说加以考查()

    >>> tp1 = “My name is {0},and I am {1} years old,I am
{2}”

  >>> tp1.format(“Alex”,”18″,”sb”)

    ‘My name is Alex,and I am 18 years old,I am sb’

    >>> tp2 = “I am {1} years old,my name is {2},and I am
{0}.”

  >>> tp2.format(“sb”,”18″,”Alex”)
  ’I am 18 years old,my name is Alex,and I am sb.’
   
这种方法也得以用在字符串的拼接上边,使用字符串的format(卡塔尔(قطر‎方法,在{}大括号中定义索引,告诉Python把哪些值传给索引地方。

    5.__getattribute__(self,*args,**kwargs)

    def __getattribute__(self, *args, **kwargs): # real
signature unknown
    ””” Return getattr(self, name). “””

        “””反射的时候用的”””
    pass

    6.__getitem__(self,*args,**kwargs)

    def __getitem__(self, *args, **kwargs): # real signature
unknown
    ””” Return self[key]. “””

    ”””获得字符串低档个因素,等价于self[key]”””
    pass  

   
正是拿到字符串中第多少个职责的字符,我们领略字符串在内部存款和储蓄器中是以列表方式储存的,因此得以使用索引来获取单个字符,实举例下:

    >>> name = “Alexissb”
  >>> name.__getitem__(2)
  ’e’
  >>> name[2]
  ’e’
    字符串中索引是从0最先的,获取字符串中第多少个岗位的字符。

    7.__getnewargs__(self,*args,**kwargs)

    def __getnewargs__(self, *args, **kwargs): # real signature
unknown

    ”””__getnewargs__是跟参数有关的”””
    pass

    8.__hash__(self,*args,**kwargs)

    def __hash__(self, *args, **kwargs): # real signature
unknown
    ””” Return hash(self). “””
    pass   

    9.__iter__(self,*args,**kwargs)

    def __iter__(self, *args, **kwargs): # real signature
unknown
    ””” Implement iter(self). “””
    pass

    10.__len__(self,*args,**kwargs)

    def __len__(self, *args, **kwargs): # real signature
unknown
    ””” Return len(self). “””

        “””再次回到字符串的长短,等价与len(self卡塔尔(英语:State of Qatar)”””
    pass

    实比如下:

    >>> name = “Alexissb”
  >>> name.__len__()
  8
  >>> len(name)
  8
    11.count(self,sub,start=None,end=None)
    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

   
count(self,sub,start=None,end=None卡塔尔(英语:State of Qatar)是用来计算字符串中现身一定字符的个数,返回一个子弹头,实举例下:

    >>> name = “Alexssbbafadgcxlsdgpssl”
    >>> name.count(“a”)
  2
    >>> name.count(“D”)
  0
    总括字符串中冒出钦点字符的个数,当不设偶然再次回到0。

    12.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””

    实举个例子下:

    >>> name = “李杰”
  >>> name.encode(“gbk”)
  b’\xc0\xee\xbd\xdc’
    将字符串转变为”gbk”格式,机器度和胆识别的格式。

    13.endswith(self,suffix,start=None,end=None)

    def endswith(self, suffix, start=None, end=None): # real signature
unknown; restored from __doc__
    ”””
    S.endswith(suffix[, start[, end]]) -> bool
       
字符串是或不是以钦赐的字符甘休,endswith(self,suffix,start=None,end=None卡塔尔
    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

   
endswith(self,suffix,start=None,end=None卡塔尔(英语:State of Qatar)决断字符串以有些钦点的字符甘休,假设是,则赶回布尔值True;否则重返False。

    >>> name = “Alexsssbdfgedlmnopqqsstabsc”
  >>> name.endswith(“c”)
  True
  >>> name.endswith(“s”,0,5)
  True
    14.expandtabs(self,tabsize=8)

    def expandtabs(self, tabsize=8): # real signature unknown; restored
from __doc__
    ”””
    S.expandtabs(tabsize=8) -> str
       
将字符串中的tab键转变为空格,私下认可时8个职分的空格,能够和睦安装参数
    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 “”

   
expandtabs(self,tabsize=8卡塔尔(قطر‎将字符串中的tab(\t卡塔尔(英语:State of Qatar)将转向为空格,暗中认可是转账为8个空格,能够本人安装转变为多少个空格。示比方下:

    >>> user = ”    Alex”
  >>> user.expandtabs()
  ’        Alex’
  >>> user.expandtabs(2)
  ’  Alex’
  >>> user.expandtabs(0)
  ’Alex’
  >>> user.expandtabs(tabsize=3)
  ’   Alex’
    15.find(self,sub,start=None,end=None)

    def find(self, sub, start=None, end=None): # real signature
unknown; restored from __doc__
    ”””
    S.find(sub[, start[, end]]) -> int
       
查找钦赐字符在字符串中的地点,重临地点索引,假如寻觅不到,则赶回-1(return
-1 on failure卡塔尔(قطر‎
    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
   
find(self,sub,start=None,end=None卡塔尔国查找钦赐字符在字符串中的地点,倘使找寻不到,则赶回-1(即查找字符一纸空文钦命字符串中卡塔尔,示举例下:

    >>> name
  ’Alexsssbdfgedlmnopqqsstabsc’
  >>> name.find(“s”)
  4
  >>> name.find(“s”,8,len(name)-1)
  20
  >>> name.find(“S”)
  -1
   
find(self,sub,start=None,end=None卡塔尔国查找这些字符第二遍面世的岗位索引。只查找第八个岗位索引,查找未果重临-1.
    16.index(self,sub,start=None,end=None)

    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

     
index(self,sub,start=None,end=None卡塔尔跟find(卡塔尔(英语:State of Qatar)雷同是搜索钦赐字符在字符串中之处索引,差别的是,假使index(卡塔尔(英语:State of Qatar)查找未果,则报错。查究不到报错。 
示比如下:

     >>> name
  ’Alexsssbdfgedlmnopqqsstabsc’
  >>> name.index(“s”)
  4
  >>> name.index(“s”,8,len(name)-1)
  20
  >>> name.index(“S”)
  Traceback (most recent call last):
     File “<stdin>”, line 1, in <module>
  ValueError: substring not found    
上边能够看来,index(卡塔尔(英语:State of Qatar)和find(卡塔尔(英语:State of Qatar)是形似的,都以回去寻觅字符的岗位索引,不过当index(卡塔尔(قطر‎查找不到的时候会报错。

    17.format_map(self,mapping)

    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 “”

    18.isalnum(self)

    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
   
示例如下:剖断字符串中是不是具有因素唯有数字和字母组成,alnum是单词阿尔法numeric的缩写,字母数字
    >>> name.isalnum()
  True
  >>> nums = “2233”
  >>> nums.isalnum()
  True

    19.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

   
推断字符串全体字符是还是不是都以字母alpha是单词alphabetic(字母)的缩写:  

>>> nums = “2233”
  >>> name.isalpha()
  True
  >>> nums.isalpha()
  False
    20.isdecimal(self)

    def isdecimal(self): # real signature unknown; restored from
__doc__
    ”””
    S.isdecimal() -> bool
       
借使字符串中值包括十进制的数字,则赶回True;不然再次来到布尔值False.
    Return True if there are only decimal characters in S,
    False otherwise.
    ”””
    return False

   
isdecimal(self卡塔尔(قطر‎剖断字符串中是还是不是只包含十进制的数字,假诺是,则赶回True;不然重临False。示比如下:

    >>> s1 = “a122”
  >>> s2 = “222”
  >>> s3 = “&b#s”
  >>> s1.isdecimal()
  False
  >>> s2.isdecimal()
  True
  >>> s3.isdecimal()
  False
    21.isdigit(self)
    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

   
isdigit(self卡塔尔国决断字符串中是否唯有饱含数字,即由数字构成的字符串。实譬喻下:

    >>> s1 = “a122”
  >>> s2 = “222”
  >>> s3 = “&b#s”

    >>> s1.isdigit()
  False
  >>> s2.isdigit()
  True
  >>> s3.isdigit()
  False
    22.isidentifier(self)

    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

    isidentifier(self卡塔尔,实举个例子下:

    >>> s2 = “Alex”
  >>> s3 = “list”
  >>> s2.isidentifier()
  True
  >>> s3.isidentifier()
  True
  >>> s4 = “55”
  >>> s4.isidentifier()
  False
  >>> s5 = “gengcx”
  >>> s5.isidentifier()
  True

    23.islower(self)

    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

    islower(self卡塔尔国判别字符串是或不是都以小写,

    >>> s1 = “Alex”
  >>> s2 = “23abc”
  >>> s3 = “alex”
  >>> s4 = “AlexSb&&”
  >>> s5 = “a%@”
  >>> s1.islower()
  False
  >>> s2.islower()
  True
  >>> s3.islower()
  True
  >>> s4.islower()
  False
  >>> s5.islower()
  True
    24.isnumeric(self)

    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

   
isnumeric(self卡塔尔(英语:State of Qatar)剖断字符串S中是或不是值富含数字在里头,假设是,重回True;不然再次回到False.

    >>> name = “Alex222”
  >>> nums = “234239”
  >>> num = “23se”
  >>> l1 = “2.35”
  >>> name.isnumeric()
  False
  >>> nums.isnumeric()
  True
  >>> num.isnumeric()
  False
  >>> l1.isnumeric()
  False
    25.isprintable(self)

    def isprintable(self): # real signature unknown; restored from
__doc__
    ”””
    S.isprintable() -> bool
      
判别二个字符串是还是不是里面包车型客车字符都以能够打字与印刷出来的还是字符串是空的,假若是再次来到True;否则再次来到False
    Return True if all characters in S are considered
    printable in repr() or S is empty, False otherwise.
    ”””
    return False

    isprintable(self) 

    >>> name = ”    Alex”
  >>> name.isprintable()
  False
  >>> user = “Alex”
  >>> user.isprintable()
  True

    >>> s1 = “”
    >>> s1.isprintable()
  True
    isprintable(s1卡塔尔中s1是空的字符串,不过也回到True.
    26.isspace(self)

    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

   
isspace(self卡塔尔剖断字符串中是否都以空白,如若是回到True;否则重回False。示譬如下:

    >>> s1 = ”    “
  >>> s2 = ”       “
  >>> s3 = “cs   “
  >>> s1.isspace()
  True
  >>> s2.isspace()
  True
  >>> s3.isspace()
  False
    27.istitle(self)

    def istitle(self): # real signature unknown; restored from
__doc__
    ”””
    S.istitle() -> bool
        推断字符串中颇负字符是还是不是是首字母大写情势,若是是回到True
    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

   
istitle(self)认清是或不是首字母大写,假诺是回到True;不然重回False。实譬喻下:

    >>> s1 = “Alex is sb”
  >>> s2 = “Alex Is Sb”
  >>> s3 = “alex is sb”
  >>> s1.istitle()
  False
  >>> s2.istitle()
  True
  >>> s3.istitle()
  False
    28.isupper(self)

    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
      isupper(self卡塔尔(英语:State of Qatar)剖断字符串中有所字符是不是都以大写情势:实比方下:

    >>> s1 = “Alex is sb”
  >>> s2 = “Alex Is Sb”
    >>> s3 = “alex is sb”

    >>> s4 = “ALEX IS SB”
    >>> s1.isupper()
  False
  >>> s2.isupper()
  False
  >>> s3.isupper()
  False

    >>> s4.isupper()
  True

    29.join(self,iterable)

    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 “”
   
join(self,iterable卡塔尔国拼接,字符串和列表直接的拼凑,有不一样方法的拼凑,下边来研商一下:

    >>> sign = “-“
  >>> name = “alex”
  >>> li = [“a”,”l”,”e”,”x”,”s”,”b”]
  >>> l1 = “”
   
1.字符串和字符串进行拼接,将拼接中的字符串的每四个元素与字符串中的成分进行拼接,即iterable+self+iterable+self… 

  >>sign.join(name)
  ’a-l-e-x’
  >>> name.join(“sb”)
  ’salexb’
  >>> name.join(“issb”)
  ’ialexsalexsalexb’
  2.字符串和列表进行拼接,列表中的每二个要素都与字符串的成分实行拼接:

  >>> sign.join(li)
  ’a-l-e-x-s-b’
  >>> l1.join(li)
  ’alexsb’

   
其实在Python中,字符串存款和储蓄的格式正是列表存款和储蓄的,比如”alexsb”存款和储蓄正是[“a”,”l”,”e”,”x”,”s”,”b”],因此字符串与列表拼接与字符串与字符串拼接是相仿的。

    30.ljust(self,width,fillchar=None)

    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 “”
    ljust(self,width,fillchar=None卡塔尔(英语:State of Qatar),固定长度,self+fillchar,实比如下:

    >>> name = “alexsb”
    >>> name.ljust(12,”-“)
  ’alexsb——‘

    31.rjust(self,width,fillchar=None)

    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 “”
    固定字符串长度,在字符串侧面链接钦定字符,实比方下:

    >>> name = “alexsb”   

  >>> name.rjust(12,”-“)
  ’——alexsb’

    32.lower(self)

    def lower(self): # real signature unknown; restored from
__doc__
    ”””
    S.lower() -> str
        将字符串全体转载为小写情势
    Return a copy of the string S converted to lowercase.
    ”””
    return “”
    33.lstrip(self,chars=None)

    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 “”
   
lstrip(self,chars=None卡塔尔国是删除字符串左侧的空格,私下认可是删除空格,其实能够钦赐删除任何字符,实举例下:

    >>> name = ”   AlexAesbb   “
  >>> name.lstrip()
  ’AlexAesbb   ‘

    34.rstrip(self,chars=None)

    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 “”
    rstrip(self,chars=None卡塔尔(قطر‎删除字符串右边的空格,实比如下:

    >>> name = ”   AlexAesbb   ”   

    >>> name.rstrip()
‘   AlexAesbb’

    35.strip(self,chars=None)

    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 “”
     strip(self,chars=None卡塔尔国删除字符串两边的空格,示例如下:

    >>> name = ”   AlexAesbb   ”   

    >>> name.strip()
  ’AlexAesbb’

    36.maketrans(self,*args,**kwargs)

    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
    37.translate(self,table)

    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 “”
    示举例下:

    >>> intab = “aeiou”
  >>> outtab = “12345”

    >>> trantab = intab.maketrans(intab,outtab)
  >>> trantab
  {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}

    >>> str = “This is string example …. wow!!!”
    >>> str.translate(trantab)
  ’Th3s 3s str3ng 2x1mpl2 …. w4w!!!’

   
上边代码含义是,把intab中各个成分与outtab中每种成分风姿罗曼蒂克风流罗曼蒂克对应,然后translate(卡塔尔替换此中对应的因素。

    38.partition(self,sep)

    def partition(self, sep): # real signature unknown; restored from
__doc__
    ”””
    S.partition(sep) -> (head, sep, tail)
        字符串分隔,以sep分隔为前中后三部分
    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
   
partition(self,sep卡塔尔字符串分隔,以字符串sep分隔为前中后三部分,并且以找到的率先个字符为分隔:

    >>> name = ‘   AlexAesbb   ‘
  >>> name.partition(“x”)
  (‘   Ale’, ‘x’, ‘Aesbb   ‘)
  >>> name.partition(“A”)
  (‘   ‘, ‘A’, ‘lexAesbb   ‘)

    39.replace(self,old,new,count=None)

    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 “”
   
字符串的交替,old哪个字符要替换,new替换来什么,count替换多少个,实比如下:

    >>> name = ‘   AlexAesbb   ‘
  >>> name.replace(“A”,”M”)
  ’   MlexMesbb   ‘
  >>> name.replace(“A”,”M”,1)
  ’   MlexAesbb   ‘

    字符串的物色替换,私下认可替换全体,能够钦赐替换的个数。

    39.rfind(self,sub,start=None,end=None)

    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
    从字符串右边早先查找,查找内定字符在字符串中的地点索引:实譬喻下:

    >>> name = ‘   AlexAesbb   ‘
  >>> name.rfind(“A”)
  7
  >>> name.find(“A”)
  3
  >>> name.rfind(” “)
  14

    从侧面查找钦点字符在字符串中的地点索引,纵然搜索不到再次回到-1.

    40.rindex(self,sub,start=None,end=None)

    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
   
rindex(self,sub,start=None,end=None卡塔尔从字符串左边查找指定字符的职位索引,若是寻找不到就能够报错。

    41.rpartition(self,sep)

    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
   
rpartition(self,sep卡塔尔国从字符串左侧开首查找分隔,与partition(self,sep卡塔尔适逢其会相反,示举例下,分隔字符串得到四个元组:

    >>> name = ‘   AlexAesbb   ‘
  >>> name.partition(“A”)
  (‘   ‘, ‘A’, ‘lexAesbb   ‘)
  >>> name.rpartition(“A”)
  (‘   Alex’, ‘A’, ‘esbb   ‘)

    42.rsplit(self,sep=None,maxsplit=-1)

    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 []
   
rsplit(self,sep=None,maxsplit=-1卡塔尔(قطر‎分隔字符串,并转移四个存放的列表,实举个例子下:

    >>> name = “Alexsbegcex”
  >>> name.split(“e”)
  [‘Al’, ‘xsb’, ‘gc’, ‘x’]
  >>> name.rsplit(“e”)
  [‘Al’, ‘xsb’, ‘gc’, ‘x’]

    >>> name.split(“e”,0)
  [‘Alexsbegcex’]
  >>> name.split(“e”,1)
  [‘Al’, ‘xsbegcex’]
  >>> name.split(“e”,2)
  [‘Al’, ‘xsb’, ‘gcex’]
  >>> name.split(“e”,3)
  [‘Al’, ‘xsb’, ‘gc’, ‘x’]
  >>> name.split(“e”,4)
  [‘Al’, ‘xsb’, ‘gc’, ‘x’]
  >>> name.split(“e”,-1)
  [‘Al’, ‘xsb’, ‘gc’, ‘x’]

   
以钦赐字符串分隔,并且替换钦点字符,分隔产生一个列表,能够钦点分隔字符的个数。

    43.split(self,sep=None,maxsplit=-1)

    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 []
    44.splitlines(self,keepends=None)

    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 []
   
splitlines(self,keepends=None)以”\n”换行符的款式分隔字符串,实比如下:

    >>> user = “””
  … alex
  … aoi
  … marry”””

    >>> user.splitlines()
  [”, ‘alex’, ‘aoi’, ‘marry’]

    45.startswith(self,prefix,start=None,end=None)

    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
   
startswith(self,prefix,start=None,end=None卡塔尔决断字符串是不是以钦命字符最初,能够钦赐起初地点,与endswith(self,prefix,start=None,end卡塔尔

无独有偶相反,示比方下:

    >>> name = ‘Alexsbegcex’
    >>> name.startswith(“A”)
  True
    >>> name.startswith(“w”)
  False

    >>> name.startswith(“e”,2,5)
  True

    46.swapcase(self)

    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 “”
   
swapcase(self卡塔尔将三个字符串中兼有字符小写转变为大写,大写转变为小写,好贱呀那些措施,实例如下:

    >>> name = ‘Alexsbegcex’
  >>> name.swapcase()
  ’aLEXSBEGCEX’

    47.title(self)

    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 “”
    48.upper(self)

    def upper(self): # real signature unknown; restored from
__doc__
    ”””
    S.upper() -> str
        将字符串全体字母都更动为题写
    Return a copy of S converted to uppercase.
    ”””
    return “”
    49.zfill(self,width)

    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 “”
    zfill(self,width卡塔尔(قطر‎内定宽度,不足左边补0,不然不改变。实举例下:

    >>> name = ‘Alexsbegcex’
  >>> name.zfill(20)
  ’000000000Alexsbegcex’
  >>> name.zfill(5)
  ’Alexsbegcex’
    50.__contains__(self,*args,**kwargs)

    def __contains__(self, *args, **kwargs): # real signature
unknown
    ””” Return key in self. “””

        判定字符串中是否富含钦定字符
    pass
   
__contains__(self,*args,**kwargs卡塔尔剖断字符串中是还是不是富含钦点字符,实比如下:

    >>> name = ‘Alexsbegcex’
  >>> name.__contains__(“e”)
  True
  >>> name.__contains__(“E”)
  False

   
 

 

字符串是编制程序中常用的门类,字符型在内部存款和储蓄器中是以单个格局储存的,比如name =
“alex”,在内部存款和储蓄器中蕴藏的花样为…

语法

find(卡塔尔(قطر‎方德文法:

str.find(str, beg=0, end=len(string))

 

参数

  • encoding — 要接受的编码,如: UTF-8。
  • errors — 设置不一致错误的拍卖方案。默以为’strict’,意为编码错误引起四个UnicodeError。 别的大概得值有 ‘ignore’,
    ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 以至通过
    codecs.register_error(卡塔尔国 注册的其余值。

参数

  • str — 钦赐检索的字符串
  • beg — 带头索引,默许为0。
  • end — 停止索引,私下认可为字符串的尺寸。

返回值

该情势重临编码后的字符串,它是叁个 bytes 对象。

返回值

假诺带有子字符串重返早前的索引值,不然重回-1。

实例

以下实例呈现了encode(卡塔尔国方法的实例:

#!/usr/bin/python3

str = "菜包python";
str_utf8 = str.encode("UTF-8")
str_gbk = str.encode("GBK")

print(str)

print("UTF-8 编码:", str_utf8)
print("GBK 编码:", str_gbk)

print("UTF-8 解码:", str_utf8.decode('UTF-8','strict'))
print("GBK 解码:", str_gbk.decode('GBK','strict'))

以上实例输出结果如下:

菜包python
UTF-8 编码: b'\xe8\x8f\x9c\xe5\x8c\x85python'
GBK 编码: b'\xb2\xcb\xb0\xfcpython'
UTF-8 解码: 菜包python
GBK 解码: 菜包python

 

实例

以下实例显示了find(卡塔尔(قطر‎方法的实例:

#!/usr/bin/python3

str1 = "Runoob example....wow!!!"
str2 = "exam";

print (str1.find(str2))
print (str1.find(str2, 5))
print (str1.find(str2, 10))

 

以上实例输出结果如下:

7
7
-1

实例

>>>info = 'abca'
>>> print(info.find('a'))      # 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0
0
>>> print(info.find('a', 1))   # 从下标1开始,查找在字符串里第一个出现的子串:返回结果3
3
>>> print(info.find('3'))      # 查找不到返回-1
-1
>>>

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图