威尼斯人娱乐官网:str字符串 find( 卡塔尔(英语:State of Qatar) 方法

1.粗略利用

字符串类型格式化接受format(卡塔尔国方法,基本采纳格式是:

     <模板字符串>.format(<逗号分隔的参数>卡塔尔

调用format(卡塔尔国方法后会再次回到二个新的字符串,参数从0 开首编号。

"{}:计算机{}的CPU 占用率为{}%。".format("2016-12-31","PYTHON",10)
Out[10]: '2016-12-31:计算机PYTHON的CPU 占用率为10%。'

 

format(卡塔尔国方法能够十分有利地连接不一样种类的变量或内容,固然要求输出大括号,接收{{表示{,}}表示},比方:

"{}{}{}".format("圆周率是",3.1415926,"...")
Out[11]: '圆周率是3.1415926...'

"圆周率{{{1}{2}}}是{0}".format("无理数",3.1415926,"...")
Out[12]: '圆周率{3.1415926...}是无理数'

s="圆周率{{{1}{2}}}是{0}" #大括号本身是字符串的一部分

s
Out[14]: '圆周率{{{1}{2}}}是{0}'

s.format("无理数",3.1415926,"...") #当调用format()时解析大括号
Out[15]: '圆周率{3.1415926...}是无理数'

 

format方法被用于字符串的格式化输出。

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

描述

find(卡塔尔 方法检查实验字符串中是否含有子字符串 str ,就算钦赐 beg(起首) 和
end(甘休)
范围,则检查是否带有在钦点范围内,假诺钦定范围内固然含有钦定索引值,重返的是索引值在字符串中的起首地方。借使不包涵索引值,重返-1。

Python中字符串格式化str.format的详尽介绍,pythonstr.format

前言

Python 在 2.6 版本中新加了叁个字符串格式化方法: str.format()
。它的骨干语法是因此 {} 和 : 来代替原先的 %.。

格式化时的占位符语法:

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"

“映射”规则

通过岗位

str.format()能够担任不限个参数,地方能够不按梯次:

>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'

经过重大字参数

运用首要参数时字符串中须要提供参数名:

>>> "I am {name}, age is {age}".format(name="huoty", age=18)
'I am huoty, age is 18'
>>> user = {"name": "huoty", "age": 18}
>>> "I am {name}, age is {age}".format(**user)
'I am huoty, age is 18'

因而对象属性

str.format()可以一向读取客商属性:

>>> class User(object):
...  def __init__(self, name, age):
...   self.name = name
...   self.age = age
...   
...  def __str__(self):
...   return "{self.name}({self.age})".format(self=self)
...  
...  def __repr__(self):
...   return self.__str__()
...  
...
>>> user = User("huoty", 18)
>>> user
huoty(18)
>>> "I am {user.name}, age is {user.age}".format(user=user)
'I am huoty, age is 18'

由此下标

在急需格式化的字符串内部能够透过下标来访谈成分:

>>> names, ages = ["huoty", "esenich", "anan"], [18, 16, 8]
>>> "I am {0[0]}, age is {1[2]}".format(names, ages)
'I am huoty, age is 8'
>>> users = {"names": ["huoty", "esenich", "anan"], "ages": [18, 16, 8]}
>>> "I am {names[0]}, age is {ages[0]}".format(**users)

点名转变

能够钦赐字符串的转向项目:

 conversion ::= "r" | "s" | "a"

其中 “!r” 对应 repr(); “!s” 对应 str(); “!a” 对应 ascii()。 示例:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

格式限制符

填充与对齐

填充常跟对齐一齐使用。^, <, >
分别是居中、左对齐、右对齐,前边带宽度, :
号前边带填充的字符,只可以是四个字符,不钦命则暗许是用空格填充。

>>> "{:>8}".format("181716")
' 181716'
>>> "{:0>8}".format("181716")
'00181716'
>>> "{:->8}".format("181716")
'--181716'
>>> "{:-<8}".format("181716")
'181716--'
>>> "{:-^8}".format("181716")
'-181716-'
>>> "{:-<25}>".format("Here ")
'Here -------------------->'

浮点精度

用 f 表示浮点类型,并得以在其前面加上精度调整:

>>> "[ {:.2f} ]".format(321.33345)
'[ 321.33 ]'
>>> "[ {:.1f} ]".format(321.33345)
'[ 321.3 ]'
>>> "[ {:.4f} ]".format(321.33345)
'[ 321.3335 ]'
>>> "[ {:.4f} ]".format(321)
'[ 321.0000 ]'

还足认为浮点数钦命符号,+ 表示在正数前展现 +,负数前显示 -;
(空格)表示在正数前加空格,在幅负数前加 -;-
与哪些都不加({:f})时相近:

>>> '{:+f}; {:+f}'.format(3.141592657, -3.141592657)
'+3.141593; -3.141593'
>>> '{: f}; {: f}'.format(3.141592657, -3.141592657)
' 3.141593; -3.141593'
>>> '{:f}; {:f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:-f}; {:-f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:+.4f}; {:+.4f}'.format(3.141592657, -3.141592657)
'+3.1416; -3.1416'

点名进制

>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(18)
'int: 18; hex: 12; oct: 22; bin: 10010'
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(18)
'int: 18; hex: 0x12; oct: 0o22; bin: 0b10010'

千位分隔符

能够使用 “,” 来作为千位分隔符:

>>> '{:,}'.format(1234567890)
'1,234,567,890'

比例显得

>>> "progress: {:.2%}".format(19.88/22)
'progress: 90.36%'

事实上,format 还帮忙越来越多的品种符号:

type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

别的本事

占位符嵌套

好何时候占位符嵌套依然很有用的:

>>> '{0:{fill}{align}16}'.format("hello", fill='*', align='^')
'*****hello******'
>>>
>>> for num in range(5,12):
...  for base in "dXob":
...   print("{0:{width}{base}}".format(num, base=base, width=5), end=' ')
...  print()
...  
...
 5  5  5 101
 6  6  6 110
 7  7  7 111
 8  8 10 1000
 9  9 11 1001
 10  A 12 1010
 11  B 13 1011

用作函数使用

能够先不点名格式化参数,而是在毫无的地点作为函数来调用:

>>> email_f = "Your email address was {email}".format
>>> print(email_f(email="[email protected]"))
Your email address was [email protected]

转义大括号

当在字符串中须要利用大括号时可以用大括号转义:

>>> " The {} set is often represented as { {0} } ".format("empty")
' The empty set is often represented as {0} '

总结

以上便是那篇文章的全体内容了,希望本文的剧情对大家的学习或然办事能推动一定的佑助,若是有问号大家可以留言沟通,多谢大家对帮客之家的支持。

前言 Python 在 2.6 版本中新加了八个字符串格式化方法: str.format(卡塔尔(英语:State of Qatar)。它的大旨语法是…

2. 格式调节音信

   format(卡塔尔方法中<模板字符串>的槽除了席卷参数序号,还是可以满含格式调节消息。这时候,槽的中间样式如下:

     {<参数序号>: <格式调节标识>}

     当中,<格式调节标志>用来调节参数字呈现示时的格式,富含:<填充><对齐><宽度>,<.精度><类型>6
个字段,这个字段都以可选的,可以整合使用,逐个介绍如下。

 

威尼斯人娱乐官网 1

 

<宽度>

指当前槽的设定输出字符宽度,如若该槽对应的format(卡塔尔(قطر‎参数长度比<宽度>设定值大,则接收参数实际尺寸。借使该值的实际位数小于钦赐宽度,则位数将被默许以空格字符补充。

<对齐>

指参数在<宽度>内输出时的对齐方式,分别使用<、>和^多个标记表示左对齐、右对齐和居中对齐。

<填充>

指<宽度>内除了参数外的字符选拔什么样措施意味着,默许使用空格,能够通过<填充>改造。

s = "PYTHON"

"{0:30}".format(s)
Out[17]: 'PYTHON                        '

"{0:>30}".format(s)
Out[18]: '                        PYTHON'

"{0:*^30}".format(s)
Out[19]: '************PYTHON************'

"{0:-^30}".format(s)
Out[20]: '------------PYTHON------------'

"{0:3}".format(s)
Out[21]: 'PYTHON'
 print('{0}+{1}={2}'.format(1,2,1+2))   #in

1+2=3   #out

    字符串是编制程序中常用的体系,字符型在内部存款和储蓄器中是以单个情势储存的,举例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卡塔尔是位居第1位首字母大写,别的字母比一点都不大写;而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(卡塔尔(英语:State of Qatar)方法,在{}大括号中定义索引,告诉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卡塔尔”””
    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卡塔尔国是用来总括字符串中冒出一定字符的个数,再次回到三个卡尺头,实举例下:

    >>> 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卡塔尔国判别字符串以有个别钦点的字符甘休,借使是,则赶回布尔值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卡塔尔国将中间转播为空格,暗中认可是转载为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(即查找字符不设有钦命字符串中卡塔尔(英语:State of Qatar),示举例下:

    >>> 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卡塔尔(英语:State of Qatar)查找这一个字符第一回现身的任务索引。只查找第二个职责索引,查找未果重临-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卡塔尔(英语:State of Qatar)跟find(卡塔尔同样是搜求内定字符在字符串中的地点索引,不一致的是,假使index(卡塔尔(قطر‎查找未果,则报错。检索不到报错。 
示举个例子下:

     >>> 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卡塔尔(قطر‎,固定长度,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卡塔尔(英语:State of Qatar)刚好相反,示比如下,分隔字符串获得二个元组:

    >>> 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))

 

逗号(,)

<格式调控标识>中逗号(,)用于体现数字的千位分隔符,比如:

"{0:-^20,}".format(1234567890)
Out[24]: '---1,234,567,890----'

"{0:-^20}".format(1234567890) #对比输出
Out[25]: '-----1234567890-----'

"{0:-^20,}".format(12345.67890)
Out[26]: '----12,345.6789-----'

足见字符串中山高校括号内的数字分别对应着format的多少个参数。

参数

  • str — 钦点检索的字符串
  • beg — 初阶索引,默感到0。
  • end — 甘休索引,默感觉字符串的长度。

 <.精度>

表示四个意思,由小数点(.)开头。对于浮点数,精度表示小数部分输出的有效位数。对于字符串,精度表示输出的最大尺寸。

"{0:.2f}".format(12345.67890)
Out[29]: '12345.68'

"{0:H^20.3f}".format(12345.67890)
Out[30]: 'HHHHH12345.679HHHHHH'

"{0:.4}".format("PYTHON")
Out[31]: 'PYTH'

 

返回值

设若含有子字符串重返初阶的索引值,不然再次回到-1。

<类型>

表示输出整数和浮点数类型的格式法规。对于整数类型,输出格式包含6 种:

  • b: 输出整数的二进制情势;
  • c: 输出整数对应的 Unicode 字符;
  • d: 输出整数的十进制方式;
  • o: 输出整数的八进制方式;
  • x: 输出整数的小写十一进制方式;
  • X: 输出整数的大写十一进制格局;

    “{0:b},{0:c},{0:d},{0:o},{0:x},{0:X}”.format(425)
    Out[32]: ‘110101001,Ʃ,425,651,1a9,1A9’

对于浮点数类型,输出格式满含4 种:

  • e: 输出浮点数对应的小写字母 e 的指数情势;
  • E: 输出浮点数对应的大写字母 E 的指数格局;
  • f: 输出浮点数的行业内部浮点方式;
  • %: 输出浮点数的百分格局。

     浮点数输出时尽大概利用<.精度>表示小数部分的宽度,有利于更加好调控输出格式。

"{0:e},{0:E},{0:f},{0:%}".format(3.14)
Out[33]: '3.140000e+00,3.140000E+00,3.140000,314.000000%'

"{0:.2e},{0:.2E},{0:.2f},{0:.2%}".format(3.14)
Out[34]: '3.14e+00,3.14E+00,3.14,314.00%'

 

若省略数字:

实例

以下实例展现了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
>>>

 

print('{}+{}={}'.format(1,2,1+2))   #in

能够获得平等的出口结果。可是替换顺序私下认可遵照[0],[1],[2]…进行。

 

若替换{0}和{1}:

print('{1}+{0}={2}'.format(1,2,1+2))   #in

2+1=3   #out

 

输出字符串:

print('{0} am {1}'.format('i','alex'))  

i am alex   #out

 

出口参数的值:

1 length = 4
2 name = 'alex'
3 print('the length of {0} is {1}'.format(name,length))

the length of alex is 4

 

精度调控:

print('{0:.3}'.format(1/3))

0.333

 

宽窄调控:

print('{0:7}{1:7}'.format('use','python'))

use    python 

 

精宽度调控(宽度内居左卡塔尔国:

print('{0:<7.3}..'.format(1/3))   

0.333  ..

实质上精宽度调整很周边于C中的printf函数。

同理’>’为居右,’^’为居中。符号很形象。

 

补全:

 1 #!/usr/bin/python
 2 #python3.6
 3 print('{0:0>3}'.format(1)) #居右,左边用0补全
 4 print('{0:{1}>3}'.format(1,0))  #也可以这么写
 5 #当输出中文使用空格补全的时候,系统会自动调用英文空格,这可能会造成不对齐
 6 #for example
 7 blog = {'1':'中国石油大学','2':'浙江大学','3':'南京航空航天大学'}
 8 print('不对齐:')
 9 print('{0:^4}\t\t{1:^8}'.format('序号','名称'))
10 for no,name in blog.items(): #字典的items()方法返回一个键值对,分别赋值给no和name
11     print('{0:^4}\t\t{1:^8}'.format(no,name))
12 print('\n对齐:')
13 print('{0:^4}\t\t{1:{2}^8}'.format('序号','名称',chr(12288))) #chr(12288)为UTF-8中的中文空格
14 for no,name in blog.items():
15     print('{0:^4}\t\t{1:{2}^8}'.format(no,name,chr(12288)))

 

#out
001
001
不对齐:
 序号              名称   
 1               中国石油大学 
 2                浙江大学  
 3              南京航空航天大学

对齐:
 序号              名称   
 1               中国石油大学 
 2                浙江大学  
 3              南京航空航天大学

 

 

 

发表评论

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