1. 程式人生 > >python之路(1)數據類型

python之路(1)數據類型

between pty obj lean 使用字符串 add pass acc 出現次數

目錄

  • 整型
  • 布爾值
  • 字符串
  • 列表
  • 元組
  • 字典

整型(int)

  1. 將字符串轉換成整型
num = "123"
v = int(num) 

   2. 將字符串按進制位轉換成整型

num = "123"
v = int(num,base=8)

   3. 輸出將當前整數的二進制位數

num = 10
v = num.bit_length()

布爾值(bool)  

  true和false

  0和1

字符串(str)

技術分享圖片
class str(object):
    """
    str(object=‘‘) -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str

    Create a new string object from the given object. If encoding or
    errors is specified, then the object must expose a data buffer
    that will be decoded using the given encoding and error handler.
    Otherwise, returns the result of object.__str__() (if defined)
    or repr(object).
    encoding defaults to sys.getdefaultencoding().
    errors defaults to ‘strict‘.
    
""" def capitalize(self, *args, **kwargs): # real signature unknown """首字母大寫""" """ Return a capitalized version of the string. More specifically, make the first character have upper case and the rest lower case. """ pass def center(self, *args, **kwargs): # real signature unknown
""" 指定寬度,將字符填在中間,兩邊默認填充空格""" """ Return a centered string of length width. Padding is done using the specified fill character (default is a space). """ pass 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 def encode(self, *args, **kwargs): # real signature unknown """ url編碼""" """ Encode the string using the codec registered for encoding. encoding The encoding in which to encode the string. errors The error handling scheme to use for encoding errors. The 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. """ pass def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """最後子字符串是否匹配指定子字符串,相同返回true,不同返回false,可以指定起始和結束位置""" """ 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 def expandtabs(self, *args, **kwargs): # real signature unknown """將字符串中的tab符(\t)轉換8個空格,依次取8個字符,直到匹配到tab符,缺幾個空格補幾個空格""" """ Return a copy where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ pass def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """查找子字符串最低索引,找到返回索引,否則返回-1,可以指定起始和結束位置""" """ 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 def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """從右邊查找子字符串最低索引,找到返回索引,否則返回-1,可以指定起始和結束位置""" """ """ """ 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 def format(self, *args, **kwargs): # known special case of str.format """替換以{""}表示的占位符,參數使用字符串列表和key=value的形式""" """ 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 def format_map(self, mapping): # real signature unknown; restored from __doc__ """替換以{""}表示的占位符,參數使用z字典""" """ S.format_map(mapping) -> str Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{‘ and ‘}‘). """ return "" def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """查找子字符串的最低索引,找到返回索引,否則報異常信息,可以指定起始和結束位置""" """ S.index(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. Raises ValueError when the substring is not found. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """從右邊查找子字符串的最低索引,找到返回索引,否則報異常信息,可以指定起始和結束位置""" """ S.rindex(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. Raises ValueError when the substring is not found. """ return 0 def isalnum(self, *args, **kwargs): # real signature unknown """判斷是不是純字母和數字,返回boolean值""" """ Return True if the string is an alpha-numeric string, False otherwise. A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string. """ pass def isalpha(self, *args, **kwargs): # real signature unknown """判斷是不是純字母,返回boolean值""" """ Return True if the string is an alphabetic string, False otherwise. A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string. """ pass def isascii(self, *args, **kwargs): # real signature unknown """判斷是不是ascii值,返回boolean值""" """ Return True if all characters in the string are ASCII, False otherwise. ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too. """ pass def isdecimal(self, *args, **kwargs): # real signature unknown """判斷是不是十進制數字符串,返回boolean值""" """ Return True if the string is a decimal string, False otherwise. A string is a decimal string if all characters in the string are decimal and there is at least one character in the string. """ pass def isdigit(self, *args, **kwargs): # real signature unknown """判斷是不是數字字符串,返回boolean值""" """ Return True if the string is a digit string, False otherwise. A string is a digit string if all characters in the string are digits and there is at least one character in the string. """ pass def isidentifier(self, *args, **kwargs): # real signature unknown """判斷是不是python標識符(字母,下劃線和數字,不能以數字開頭),返回boolean值""" """ Return True if the string is a valid Python identifier, False otherwise. Use keyword.iskeyword() to test for reserved identifiers such as "def" and "class". """ pass def islower(self, *args, **kwargs): # real signature unknown """判斷是不是小寫,返回boolean值""" """ Return True if the string is a lowercase string, False otherwise. A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string. """ pass def isnumeric(self, *args, **kwargs): # real signature unknown """判斷是不是數字字符,返回boolean值,認識阿拉伯數字之外的數字字符""" """ Return True if the string is a numeric string, False otherwise. A string is numeric if all characters in the string are numeric and there is at least one character in the string. """ pass def isprintable(self, *args, **kwargs): # real signature unknown """ 判斷是否有轉義字符存在,返回boolean值""" """ Return True if the string is printable, False otherwise. A string is printable if all of its characters are considered printable in repr() or if it is empty. """ pass def isspace(self, *args, **kwargs): # real signature unknown """判斷是不是空格,返回boolean值""" """ Return True if the string is a whitespace string, False otherwise. A string is whitespace if all characters in the string are whitespace and there is at least one character in the string. """ pass def istitle(self, *args, **kwargs): # real signature unknown """判斷是不是標題(每個單詞首字母大寫),返回boolean值""" """ Return True if the string is a title-cased string, False otherwise. In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones. """ pass def isupper(self, *args, **kwargs): # real signature unknown """判斷是不是大寫,返回boolean值""" """ Return True if the string is an uppercase string, False otherwise. A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string. """ pass def join(self, ab=None, pq=None, rs=None): # real signature unknown; restored from __doc__ """將字符填充到給定字符串的每個字符之間""" """ Concatenate any number of strings. The string whose method is called is inserted in between each given string. The result is returned as a new string. Example: ‘.‘.join([‘ab‘, ‘pq‘, ‘rs‘]) -> ‘ab.pq.rs‘ """ pass def ljust(self, *args, **kwargs): # real signature unknown """在字符串的右邊填充字符""" """ Return a left-justified string of length width. Padding is done using the specified fill character (default is a space). """ pass def rjust(self, *args, **kwargs): # real signature unknown """在字符串的左邊填充字符""" """ Return a right-justified string of length width. Padding is done using the specified fill character (default is a space). """ pass def lower(self, *args, **kwargs): # real signature unknown """字母小寫""" """ Return a copy of the string converted to lowercase. """ pass def upper(self, *args, **kwargs): # real signature unknown """字母大寫""" """ Return a copy of the string converted to uppercase. """ pass def casefold(self, *args, **kwargs): # real signature unknown """" 將大寫轉換成小寫 適用其他國家的語法""" """ Return a version of the string suitable for caseless comparisons. """ pass def lstrip(self, *args, **kwargs): # real signature unknown """刪除從左邊匹配的字符串""" """ Return a copy of the string with leading whitespace removed. If chars is given and not None, remove characters in chars instead. """ pass def maketrans(self, *args, **kwargs): # real signature unknown """設置字符的對應關系,與translate連用""" """ 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 def translate(self, *args, **kwargs): # real signature unknown """根據對應關系,翻譯字符串""" """ Replace each character in the string using the given translation table. table Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None. The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted. """ pass def partition(self, *args, **kwargs): # real signature unknown """指定字符切割""" """ Partition the string into three parts using the given separator. This will search for the separator in the string. 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 string and two empty strings. """ pass def rpartition(self, *args, **kwargs): # real signature unknown """從右邊指定字符切割""" """ Partition the string into three parts using the given separator. This will search for the separator in the string, starting at the end. 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 two empty strings and the original string. """ pass def replace(self, *args, **kwargs): # real signature unknown """用新字符串,替換舊字符串,默認全部替換""" """ Return a copy with all occurrences of substring old replaced by new. count Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences. If the optional argument count is given, only the first count occurrences are replaced. """ pass def rsplit(self, *args, **kwargs): # real signature unknown """指定字符從右邊分割字符串,可指定最大分割""" """ Return a list of the words in the string, using sep as the delimiter string. sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit. Splits are done starting at the end of the string and working to the front. """ pass def split(self, *args, **kwargs): # real signature unknown """指定字符分割字符串,可指定最大分割""" """ Return a list of the words in the string, using sep as the delimiter string. sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit. """ pass def splitlines(self, *args, **kwargs): # real signature unknown """根據換行(\n)分割,true指定保留換行,false不保留""" """ Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ pass def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ """判斷是不是指定字符串開頭,指定起始和結束位置,返回Boolean值""" """ 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 def strip(self, *args, **kwargs): # real signature unknown """刪除左右兩邊匹配的字符串""" """ Return a copy of the string with leading and trailing whitespace remove. If chars is given and not None, remove characters in chars instead. """ pass def rstrip(self, *args, **kwargs): # real signature unknown """刪除從右邊匹配的字符串""" """ Return a copy of the string with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ pass def swapcase(self, *args, **kwargs): # real signature unknown """大小寫轉換""" """ Convert uppercase characters to lowercase and lowercase characters to uppercase. """ pass def title(self, *args, **kwargs): # real signature unknown """每個單詞開頭大寫""" """ Return a version of the string where each word is titlecased. More specifically, words start with uppercased characters and all remaining cased characters have lower case. """ pass def zfill(self, *args, **kwargs): # real signature unknown """從左邊填充0""" """ Pad a numeric string with zeros on the left, to fill a field of the given width. The string is never truncated. """ pass
str_method

列表(list)

   [‘a‘,‘b‘,‘c‘,‘d‘]

   1. 切片

技術分享圖片
test = [a,b,c,d]
v = test[0:3]
View Code

   2. 刪除

技術分享圖片
del test[2]
View Code

   3. 判斷元素是否在列表中

技術分享圖片
v = a in test
View Code

  4. 轉換list的條件為可叠代

技術分享圖片
v = list("abcdef")
View Code

  list方法

技術分享圖片
class list(object):
    """
    Built-in mutable sequence.

    If no argument is given, the constructor creates a new empty list.
    The argument must be an iterable if specified.
    """

    def append(self, *args, **kwargs):  # real signature unknown
        """在後面追加items"""
        """ Append object to the end of the list. """
        pass

    def clear(self, *args, **kwargs):  # real signature unknown
        """清空"""
        """ Remove all items from list. """
        pass

    def copy(self, *args, **kwargs):  # real signature unknown
        """復制"""
        """ Return a shallow copy of the list. """
        pass

    def count(self, *args, **kwargs):  # real signature unknown
        """返回值的出現次數"""
        """ Return number of occurrences of value. """
        pass

    def extend(self, *args, **kwargs):  # real signature unknown
        """通過附加iterable中的元素來擴展列表"""
        """ Extend list by appending elements from the iterable. """
        pass

    def index(self, *args, **kwargs):  # real signature unknown
        """返回找到第一個值的索引,沒找到報錯"""
        """
        Return first index of value.

        Raises ValueError if the value is not present.
        """
        pass

    def insert(self, *args, **kwargs):  # real signature unknown
        """插入指定位置元素"""
        """ Insert object before index. """
        pass

    def pop(self, *args, **kwargs):  # real signature unknown
        """刪除指定索引的value,並返回value,不指定索引,默認刪除最後"""
        """
        Remove and return item at index (default last).

        Raises IndexError if list is empty or index is out of range.
        """
        pass

    def remove(self, *args, **kwargs):  # real signature unknown
        """刪除列表指定value,左邊優先"""
        """
        Remove first occurrence of value.

        Raises ValueError if the value is not present.
        """
        pass

    def reverse(self, *args, **kwargs):  # real signature unknown
        """翻轉列表的值"""
        """ Reverse *IN PLACE*. """
        pass

    def sort(self, *args, **kwargs):  # real signature unknown
        """排序"""
        """ Stable sort *IN PLACE*. """
        pass
list_method

元組(tuple)

  (‘a‘,‘b‘,‘c‘,‘d‘)

  1. 元組不可修改

  tuple方法

技術分享圖片
class tuple(object):
    """
    Built-in immutable sequence.

    If no argument is given, the constructor returns an empty tuple.
    If iterable is specified the tuple is initialized from iterable‘s items.

    If the argument is a tuple, the return value is the same object.
    """

    def count(self, *args, **kwargs):  # real signature unknown
        """返回值的出現次數"""
        """ Return number of occurrences of value. """
        pass

    def index(self, *args, **kwargs):  # real signature unknown
        """返回找到第一個值的索引,沒找到報錯"""
        """
        Return first index of value.

        Raises ValueError if the value is not present.
        """
        pass
tuple_method

字典(dict)

  { ‘a’:111, ‘b‘:111, ‘c‘:111, ‘d‘:111 }

  dlct的方法

技術分享圖片
class dict(object):
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object‘s
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    """

    def clear(self):  # real signature unknown; restored from __doc__
        """清空"""
        """ D.clear() -> None.  Remove all items from D. """
        pass

    def copy(self):  # real signature unknown; restored from __doc__
        """拷貝"""
        """ D.copy() -> a shallow copy of D """
        pass

    @staticmethod  # known case靜態方法
    def fromkeys(*args, **kwargs):  # real signature unknown
        """使用來自iterable和值設置為value的鍵創建一個新字典"""
        """ Create a new dictionary with keys from iterable and values set to value. """
        pass

    def get(self, *args, **kwargs):  # real signature unknown
        """如果key在字典中,則返回key的值,否則返回default。"""
        """ Return the value for key if key is in the dictionary, else default. """
        pass

    def items(self):  # real signature unknown; restored from __doc__
        """獲取字典裏所有的鍵值對"""
        """"""
        """ D.items() -> a set-like object providing a view on D‘s items """
        pass

    def keys(self):  # real signature unknown; restored from __doc__
        """獲取字典裏所有的key"""
        """ D.keys() -> a set-like object providing a view on D‘s keys """
        pass

    def pop(self, k, d=None):  # real signature unknown; restored from __doc__
        """刪除指點key的值,並返回value,如果key沒找到,返回默認值"""
        """
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
        """
        pass

    def popitem(self):  # real signature unknown; restored from __doc__
        """刪除鍵值對,並返回鍵值對"""
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass

    def setdefault(self, *args, **kwargs):  # real signature unknown
        """如果鍵不在字典中,則插入值為default的值。
            如果key在字典中,則返回key的值,否則返回default。"""
        """
        Insert key with a value of default if key is not in the dictionary.

        Return the value for key if key is in the dictionary, else default.
        """
        pass

    def update(self, E=None, **F):  # known special case of dict.update
        """更新字典,參數可以是字典和‘key=value,key2=value2...’"""
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass

    def values(self):  # real signature unknown; restored from __doc__
        """獲得字典的values"""
        """ D.values() -> an object providing a view on D‘s values """
        pass
dict_method

python之路(1)數據類型