Python3.6.4的str的源代码

在Python的IDE工具pycharm中可以输入数据类型的名称后,ctrl + B,数据类型的源代码。str的部分源代码如下:

str类的方法

  1. capitailize:字符串的首字母大写
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 ""

方法实例:

>>> test = "title"
>>> v = test.capitalize()
>>> print(v)
Title
  1. casefold:将字符串全部转换为小写,不仅仅识别英文!
def casefold(self): # real signature unknown; restored from __doc__
    """
    S.casefold() -> str

    Return a version of S suitable for caseless comparisons.
    """
    return ""

方法实例:

>>> test = "Case One"
>>> v = test.casefold()
>>> print(v)
case one
  1. 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 ""

用法实例:

>>> test = "test"
>>> v = test.center(20,"-")
>>> print(v)
--------test--------
  1. 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 ""

用法实例

>>> string = "test"
>>> print(string.ljust(20,"-"))
test----------------
  1. 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 ""

用法实例

>>> string = "test"
>>> print(string.rjust(20,"-"))
----------------test
  1. zfill:设定字符串的长度,并以数字“0”对字符串进行右对齐
def zfill(self, width): # real signature unknown; restored from __doc__
    """
    S.zfill(width) -> str

    Pad a numeric string S with zeros on the left, to fill a field
    of the specified width. The string S is never truncated.
    """
    return ""

用法实例

>>> string = "test"
>>> print(string.zfill(20))
0000000000000000test
  1. 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

用法实例:

>>> test = "high school student"
>>> v1 = test.count("s")
>>> v2 = test.count("s",0,12)
>>> print(v1,v2,sep="\n")
2
1
  1. 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

用法实例:

>>> string = 'hello world'
>>> print(string.endswith("ld"))
True
  1. startswith:判断字符串是否以指定字符开始
def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
    """
    B.startswith(prefix[, start[, end]]) -> bool

    Return True if B starts with the specified prefix, False otherwise.
    With optional start, test B beginning at that position.
    With optional end, stop comparing B at that position.
    prefix can also be a tuple of bytes to try.
    """
    return False

用法实例

>>> string = 'hello world'
>>> print(string.startswith("hi"))
False
  1. expandtabs:已指定长度对字符串进行对齐。常用于制表
def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
    """
    B.expandtabs(tabsize=8) -> copy of B

    Return a copy of B where all tab characters are expanded using spaces.
    If tabsize is not given, a tab size of 8 characters is assumed.
    """
    pass

用法实例

>>> string = '1234567\t89'
>>> print(string.expandtabs(6))
1234567     89

在上面的例子中,expandtabs的作用是:对字符串的内容每6个检查一次,如果6个字符中没有出现制表符tab,则不做任何操作,继续往下1个6个字符继续查找。数字“7”后后面出现\t,则这里\t表示5个空格。

>>> string = 'username\tage\tweight\nliu\t21\t59kg\nhao\t23\t62kg\nhai\t23\t59kg'
>>> print(string.expandtabs(20))
username            age                 weight
liu                 21                  59kg
hao                 23                  62kg
hai                 23                  59kg
  1. find:从左往右,查找指定字符在字符串中第一次出现的位置(下标)。同样区间范围是左开右闭
def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
    """
    B.find(sub[, start[, end]]) -> int

    Return the lowest index in B where subsection sub is found,
    such that sub is contained within B[start,end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.
    """
    return 0

用法实例

>>> string = "asdfuioas"
>>> l = len(string)
>>> s1 = string.find("a")
>>> s2 = string.find("a",7)
>>> s3 = string.find("x")
>>> print(s1,s2,s3)
0 7 -1

其中,s2表示从下标7开始查找。如果在字符串中没有找对指定的字符,其返回值为“-1”。

  1. index:功能和find相同,但是如果在字符串中没有找对指定的字符,会报错。一般常使用find
>>> string = "asdfuioas"
>>> print(string.index("x"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
  1. 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

用法实例

>>> string = "I am {name},I am {age} year old"
>>> print(string.format(name="haoahai",age=24))
I am haoahai,I am 24 year old
>>> string = "I am {0},I am {1} year old"
>>> print(string.format("haoahai",24))
I am haoahai,I am 24 year old
>>> string = "I am {name},I am {age} year old"
>>> print(string.format(**{"name":"haohai","age":24}))
I am haohai,I am 24 year old

在看到类的方法中,如果参数中出现“**”,表示可以使用字典形式。

  1. format_map:功能和format一致,参数使用字典的形式
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 ""

用法实例

>>> string = "I am {name},I am {age} year old"
>>> print(string.format_map({"name":"haohai","age":24}))
I am haohai,I am 24 year old
  1. 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

用法实例

>>> string = "lhh1410_"
>>> print(string.isalnum())
False
  1. 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

用法实例

>>> print(string.isalpha())
False
  1. 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

用法实例

>>> string1 = "123"
>>> string2 = "②"
>>> print(string1.isdecimal(),string2.isdecimal(),sep="\n")
True
False
  1. 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

用法实例

>>> string2 = "②"
>>> print(string2.isdecimal(),string2.isdigit(),sep="\n")
False
True
  1. 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

用法实例

>>> string = "二"
>>> print(string.isdigit(),string.isnumeric())
False True

当我们在判断一个文件中的中文几级标题时,可以利用decimal和digit的判断是False并且isnumeric是True时来一起判定中文的标题

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

用法实例

>>> string1 = "0jump"
>>> string2 = "_0jump"
>>> print(string1.isidentifier(),string2.isidentifier())
False True
  1. 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

用法实例

>>> string = "1234567\t98"
>>> print(string.isprintable())
False
  1. 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

用法实例

>>> string1 = "hao hai"
>>> string2 = "   "
>>> print(string1.isspace(),string2.isspace())
False True
  1. 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

用法实例

>>> string = "@-=+liu"
>>> print(string.islower())
True
  1. lower:将字符串中的字母转换成小写
def lower(self): # real signature unknown; restored from __doc__
    """
    S.lower() -> str

    Return a copy of the string S converted to lowercase.
    """
    return ""

用法实例

>>> string = "Hurst_Liu"
>>> print(string.lower())
hurst_liu
  1. isupper:判断字符串中的字母是否全部为大写
def isupper(self): # real signature unknown; restored from __doc__
    """
    B.isupper() -> bool

    Return True if all cased characters in B are uppercase and there is
    at least one cased character in B, False otherwise.
    """
    return False

用法实例

>>> string = "HURST_"
>>> print(string.isupper())
True
  1. upper:将字符串中的字母全部转换为大写
def upper(self): # real signature unknown; restored from __doc__
    """
    S.upper() -> str

    Return a copy of S converted to uppercase.
    """
    return ""

用法实例

>>> string = "hurst_"
>>> print(string.upper())
HURST_
  1. istitle:判断字符串是否为英文标题
def istitle(self): # real signature unknown; restored from __doc__
    """
    B.istitle() -> bool

    Return True if B is a titlecased string and there is at least one
    character in B, i.e. uppercase characters may only follow uncased
    characters and lowercase characters only cased ones. Return False
    otherwise.
    """
    return False

用法实例

>>> string = "it's a good man"
>>> print(string.istitle())
False
  1. title:将字符串转换成英文标题的形式(首字母大写)
def title(self): # real signature unknown; restored from __doc__
    """
    B.title() -> copy of B

    Return a titlecased version of B, i.e. ASCII words start with uppercase
    characters, all remaining cased characters have lowercase.
    """
    pass

用法实例

>>> string = "it's a good man"
>>> print(string.title())
It'S A Good Man
  1. 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 ""

用法实例

>>> string = "nospace"
>>> print(" ".join(string))
n o s p a c e
>>> print("-".join(string))
n-o-s-p-a-c-e
  1. strip:默认去除字符串左右2边的空格,可指定去除的字符
def strip(self, *args, **kwargs): # real signature unknown
    """
    Strip leading and trailing bytes contained in the argument.

    If the argument is omitted or None, strip leading and trailing ASCII whitespace.
    """
    pass

用法实例

>>> string = "  test  "
>>> print(string.strip())
test
  1. ltrip:默认去除字符串左边的空格,可指定去除的字符
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 ""

用法实例

>>> print(string.lstrip())
test
  1. rstrip:默认去除字符串左右2边的空格,可指定去除的字符
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 ""

用法实例

>>> string = "  test  "
>>> print(string.rstrip())
  test
  1. translate:和maketrans配合使用。将字符串中的字符替换成指定字符(一对一替换,并非整体替换)
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 ""

用法实例

>>> string = "asdljdlfadfd"
>>> m = string.maketrans("asd",123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: maketrans() argument 2 must be str, not int
>>> m = string.maketrans("asd","123")
>>> new_string = string.translate(m)
>>> print(new_string)
123lj3lf13f3
  1. replace:将字符串中的字符替换成指定字符(整体替换)
def _replace(self, **kwargs):
    'Return a new named tuple object replacing specified fields with new values.'
    return self

用法实例

>>> string = "asd;a1s2d1"
>>> print(string.replace("asd","123"))
123;a1s2d1
  1. split:从左开始,将字符串按照指定分隔符分割为指定部分(不包含分隔符)
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 []

用法实例

>>> string = "asdyouarsd0s23"
>>> print(string.split("s"))
['a', 'dyouar', 'd0', '23']
>>> print(string.split("s",2))
['a', 'dyouar', 'd0s23']
  1. partition:将字符串按照指定分隔符分割成3部分,包含分隔符(当有多个分隔符时,从左往右去第一个分隔符)
def partition(self, *args, **kwargs): # real signature unknown
    """
    Partition the bytearray into three parts using the given separator.

    This will search for the separator sep in the bytearray. If the separator is
    found, returns a 3-tuple containing the part before the separator, the
    separator itself, and the part after it.

    If the separator is not found, returns a 3-tuple containing the original
    bytearray object and two empty bytearray objects.
    """
    pass

用法实例

>>> string = "asdyouarsd0s23"
>>> print(string.partition("s"))
('a', 's', 'dyouarsd0s23')

str类的通用功能

  1. 索引:通过元素的下标,来提取字符串中的元素(子串)。
>>> string = "learning python"
>>> print(len(string),string[2])
15 a

通过索引的方式可以实现字符串元素的读取操作,但由于字符串的元素是存储在连续的内存地址空间中,通过索引是无法实现字符串的修改。一旦字符串被拼接、修改后,系统会重新开辟内存地址来存放新的字符串

>>> string = "learning python"
>>> string[2] = "sd"
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
  1. 切片:提取字符串中下标连续的子序列
>>> string = "learning python"
>>> print(string[0:6],string[0:-1],sep="\n")
learni
learning pytho

“-1”表示为字符串的最后一个下标(注意右开区间的问题)

  1. 长度len:计算字符串的长度,即元素的个数
>>> string = "learning python"
>>> print(len(string))
15

注意:如果是Python3.6,len表示为元素个数;如果是Python2.7,则是字符传所占的字节数

  1. range:创建连续的序列(数字)
>>> ran = range(1,10)
>>> print(ran)
range(1, 10)

如果是Python2.7中,上述的结果会直接显示1~10这个数字,即为所有的数字序列立即分配内容地址。Python3.6有所不同,只有在正式调用时才会为子序列开辟内存空间。
range常和len配合使用,用来提取字符串(str类创建的对象)的每一个元素即元素对应的下标

string = "python"
l = len(string)
r = range(0,l)
for i in r :
print(i,string[i])
0 p
1 y
2 t
3 h
4 o
5 n
  1. for、while:提取字符串中的每一个元素
string = "python"
for i in string :
print(i)
l = len(string)
num = 0
while num < l :
print(num,string[num])
num += 1
p
y
t
h
o
n
0 p
1 y
2 t
3 h
4 o
5 n