一.基本數據類型
整數:int
字符串:str(注:\t等于一個tab鍵)
布爾值: bool
列表:list
列表用[]
元祖:tuple
元祖用()
字典:dict
注:所有的數據類型都存在想對應的類列里
二.字符串所有數據類型:
基本操作:
- 索引
- 切片
- 追加
- 刪除
- 長度
- 切片
- 循環
- 包含
class str(object):"""str(object='') -> strstr(bytes_or_buffer[, encoding[, errors]]) -> strCreate a new string object from the given object. If encoding orerrors is specified, then the object must expose a data bufferthat 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): # real signature unknown; restored from __doc__"""S.capitalize() -> strReturn a capitalized version of S, i.e. make the first characterhave upper case and the rest lower case.(返回一個大寫版本的年代,即第一個字符,有大寫,其余小寫。)"""return ""def casefold(self): # real signature unknown; restored from __doc__"""S.casefold() -> strReturn a version of S suitable for caseless comparisons.(返回一個版本的S適合caseless比較。)"""return ""def center(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.center(width[, fillchar]) -> strReturn S centered in a string of length width. Padding isdone using the specified fill character (default is a space)(返回年代集中在一個字符串的長度寬度。填充使用指定的填充字符(默認是一個空間))"""return ""def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__"""S.count(sub[, start[, end]]) -> intReturn the number of non-overlapping occurrences of substring sub instring S[start:end]. Optional arguments start and end areinterpreted as in slice notation.(返回的數量重疊出現的子串子字符串(開始:結束)。可選參數的開始和結束解釋為片符號。)"""return 0def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__"""S.encode(encoding='utf-8', errors='strict') -> bytesEncode S using the codec registered for encoding. Default encodingis 'utf-8'. errors may be given to set a different errorhandling scheme. Default is 'strict' meaning that encoding errors raisea UnicodeEncodeError. Other possible values are 'ignore', 'replace' and'xmlcharrefreplace' as well as any other name registered withcodecs.register_error that can handle UnicodeEncodeErrors."""return b""def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__"""S.expandtabs(tabsize=8) -> strReturn 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.(返回一個副本的年代,所有制表符使用空間擴大。如果tabsize不是,一個標簽大小8個字符。)"""return ""def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__"""S.find(sub[, start[, end]]) -> intReturn the lowest index in S where substring sub is found,such that sub is contained within S[start:end]. Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure.(回報指數最低的年代找到子字符串的子,這樣的子是包含在S[開始:結束]。可選參數中解釋為開始和結束符號。)"""return 0def format(self, *args, **kwargs): # known special case of str.format"""S.format(*args, **kwargs) -> strReturn a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}').(返回一個格式化的年代,利用參數的替換和kwargs。替換被括號(“{”和“}”)。)"""passdef format_map(self, mapping): # real signature unknown; restored from __doc__"""S.format_map(mapping) -> strReturn 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]]) -> intLike S.find() but raise ValueError when the substring is not found.(像S.find(),但沒有找到子字符串時提高ValueError)"""return 0def isalnum(self): # real signature unknown; restored from __doc__"""S.isalnum() -> boolReturn True if all characters in S are alphanumericand there is at least one character in S, False otherwise.(如果在年代所有的人物都是字母數字返回True和至少有一個角色年代,否則假。)"""return Falsedef isalpha(self): # real signature unknown; restored from __doc__"""S.isalpha() -> boolReturn True if all characters in S are alphabeticand there is at least one character in S, False otherwise.(如果在年代所有的人物都是字母返回True和至少有一個角色年代,否則假。)"""return Falsedef isdigit(self): # real signature unknown; restored from __doc__"""S.isdigit() -> boolReturn True if all characters in S are digitsand there is at least one character in S, False otherwise.(返回True,如果在年代所有的人物都是數字和至少有一個角色年代,否則假。)"""return Falsedef islower(self): # real signature unknown; restored from __doc__"""S.islower() -> boolReturn True if all cased characters in S are lowercase and there isat least one cased character in S, False otherwise.(返回True,如果所有S是小寫,下套管的字符至少有一個下套管在年代,否則假。)"""return Falsedef isnumeric(self): # real signature unknown; restored from __doc__"""S.isnumeric() -> boolReturn True if there are only numeric characters in S,False otherwise.(返回True,如果只有數字字符,否則錯誤。)"""return Falsedef isprintable(self): # real signature unknown; restored from __doc__"""S.isprintable() -> boolReturn True if all characters in S are consideredprintable in repr() or S is empty, False otherwise.(如果在年代所有的人物都是考慮返回True,可打印在repr()或年代是空的,否則假。)"""return Falsedef isspace(self): # real signature unknown; restored from __doc__"""S.isspace() -> boolReturn True if all characters in S are whitespaceand there is at least one character in S, False otherwise.(返回True,如果在年代所有的人物都是空白和至少有一個角色年代,否則假。)"""return Falsedef istitle(self): # real signature unknown; restored from __doc__"""S.istitle() -> boolReturn True if S is a titlecased string and there is at least onecharacter in S, i.e. upper- and titlecase characters may onlyfollow uncased characters and lowercase characters only cased ones.Return False otherwise.(返回True,如果S titlecased字符串和至少有一個個性的年代,即上,可能只titlecase字符遵循外露的字符和小寫字符只下套管。否則返回假。)"""return Falsedef isupper(self): # real signature unknown; restored from __doc__"""S.isupper() -> boolReturn True if all cased characters in S are uppercase and there isat least one cased character in S, False otherwise.(返回True,如果所有S是大寫,下套管的字符至少有一個下套管在年代,否則假。)"""return Falsedef join(self, iterable): # real signature unknown; restored from __doc__"""S.join(iterable) -> strReturn a string which is the concatenation of the strings in theiterable. The separator between elements is S.(返回一個字符串的連接字符串iterable。元素之間的分隔符是S。)"""return ""def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.ljust(width[, fillchar]) -> strReturn S left-justified in a Unicode string of length width. Padding isdone using the specified fill character (default is a space).(返回年代左對齊的Unicode字符串的長度寬度。填充使用指定的填充字符(默認值是一個空格)。)"""return ""def lower(self): # real signature unknown; restored from __doc__"""S.lower() -> strReturn a copy of the string S converted to lowercase.(返回的字符串轉換為小寫。)"""return ""def lstrip(self, chars=None): # real signature unknown; restored from __doc__"""S.lstrip([chars]) -> strReturn a copy of the string S with leading whitespace removed.If chars is given and not None, remove characters in chars instead.(返回字符串的副本刪除前導空白。如果字符而不是沒有,刪除字符字符代替。)"""return ""def partition(self, sep): # real signature unknown; restored from __doc__"""S.partition(sep) -> (head, sep, tail)Search for the separator sep in S, and return the part before it,the separator itself, and the part after it. If the separator is notfound, return S and two empty strings.(搜索分離器sep的年代,并返回之前的部分一樣,分隔符本身,后一部分。如果分隔符發現,還和兩個空字符串。)"""passdef replace(self, old, new, count=None): # real signature unknown; restored from __doc__"""S.replace(old, new[, count]) -> strReturn a copy of S with all occurrences of substringold replaced by new. If the optional argument count isgiven, only the first count occurrences are replaced.(返回一個年代出現的所有子字符串的副本老被新的取代。如果可選參數計數,只替換第一計數。)"""return ""def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__"""S.rfind(sub[, start[, end]]) -> intReturn the highest index in S where substring sub is found,such that sub is contained within S[start:end]. Optionalarguments start and end are interpreted as in slice notation. Return -1 on failure.(回報最高的指數在年代找到子字符串的子,這樣的子是包含在S[開始:結束]。可選參數中解釋為開始和結束符號。) """return 0def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__"""S.rindex(sub[, start[, end]]) -> intLike S.rfind() but raise ValueError when the substring is not found.(像S.rfind(),但沒有找到子字符串時提高ValueError。)"""return 0def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.rjust(width[, fillchar]) -> strReturn S right-justified in a string of length width. Padding isdone using the specified fill character (default is a space).(返回右對齊的在一個字符串的長度寬度。填充使用指定的填充字符(默認值是一個空格))"""return ""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 returnthe part before it, the separator itself, and the part after it. If theseparator is not found, return two empty strings and S.(尋找分離器在年代,9月開始的年代,并返回之前的部分一樣,分離器本身,后一部分。如果沒有找到分隔符,返回兩個空字符串和年代。)"""passdef rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__"""S.rsplit(sep=None, maxsplit=-1) -> list of stringsReturn a list of the words in S, using sep as thedelimiter string, starting at the end of the string andworking to the front. If maxsplit is given, at most maxsplitsplits are done. If sep is not specified, any whitespace stringis a separator.(返回一個列表的單詞,使用9月作為分隔符字符串,字符串的結束和開始工作到前面來。如果maxsplit,最多maxsplit分割完成。如果沒有指定9月,任何空白字符串是一個分隔符。)"""return []def rstrip(self, chars=None): # real signature unknown; restored from __doc__"""S.rstrip([chars]) -> strReturn a copy of the string S with trailing whitespace removed.If chars is given and not None, remove characters in chars instead.(返回一個字符串的副本年代尾隨空格移除。如果字符而不是沒有,刪除字符字符代替。)"""return ""def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__"""S.split(sep=None, maxsplit=-1) -> list of stringsReturn a list of the words in S, using sep as thedelimiter string. If maxsplit is given, at most maxsplitsplits are done. If sep is not specified or is None, anywhitespace string is a separator and empty strings areremoved from the result.(返回一個列表的單詞,使用9月作為分隔符的字符串。如果maxsplit,最多maxsplit分割完成。如果沒有指定9月或沒有,空白字符串分隔符和空字符串從結果中刪除。)"""return []def splitlines(self, keepends=None): # real signature unknown; restored from __doc__"""S.splitlines([keepends]) -> list of stringsReturn a list of the lines in S, breaking at line boundaries.Line breaks are not included in the resulting list unless keependsis given and true.(返回一個列表的行,行打破界限。換行符不包括在結果列表,除非keepends和真正的。)"""return []def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__"""S.startswith(prefix[, start[, end]]) -> boolReturn 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.(返回True,如果年代始于指定的前綴,否則假。可選的開始,測試年代開始在那個位置。帶有可選結束,停止比較年代在那個位置。前綴也可以嘗試一個元組的字符串。)"""return Falsedef strip(self, chars=None): # real signature unknown; restored from __doc__"""S.strip([chars]) -> strReturn a copy of the string S with leading and trailingwhitespace removed.If chars is given and not None, remove characters in chars instead.(返回字符串的副本與前導和尾隨空格移除。如果字符而不是沒有,刪除字符字符代替。)"""return ""def swapcase(self): # real signature unknown; restored from __doc__"""S.swapcase() -> strReturn a copy of S with uppercase characters converted to lowercaseand vice versa.(返回一個副本的年代大寫字符轉換為小寫反之亦然)"""return ""def title(self): # real signature unknown; restored from __doc__"""S.title() -> strReturn a titlecased version of S, i.e. words start with title casecharacters, all remaining cased characters have lower case.(返回一個titlecased版本的年代,即單詞從標題開始字符,所有剩余的下套管字符小寫)"""return ""def translate(self, table): # real signature unknown; restored from __doc__"""S.translate(table) -> strReturn a copy of the string S in which each character has been mappedthrough the given translation table. The table must implementlookup/indexing via __getitem__, for instance a dictionary or list,mapping Unicode ordinals to Unicode ordinals, strings, or None. Ifthis operation raises LookupError, the character is left untouched.Characters mapped to None are deleted.(返回的字符串的每個字符被映射通過給定的轉換表。表必須實現通過__getitem__查找/索引,例如字典或列表,Unicode依次映射到Unicode序數、字符串或沒有。如果此操作提出了LookupError,字符保持不變)"""return ""def upper(self): # real signature unknown; restored from __doc__"""S.upper() -> strReturn a copy of S converted to uppercase.(返回一個副本年代轉換為大寫)"""return ""def zfill(self, width): # real signature unknown; restored from __doc__"""S.zfill(width) -> strPad a numeric string S with zeros on the left, to fill a fieldof the specified width. The string S is never truncated.(墊一個數字字符串與0年代在左邊,填補一個字段指定的寬度。字符串年代不會截斷。)"""return ""def __add__(self, *args, **kwargs): # real signature unknown""" Return self+value. """passdef __contains__(self, *args, **kwargs): # real signature unknown""" Return key in self. """passdef __eq__(self, *args, **kwargs): # real signature unknown""" Return self==value. """passdef __format__(self, format_spec): # real signature unknown; restored from __doc__"""S.__format__(format_spec) -> strReturn a formatted version of S as described by format_spec."""return ""def __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __getitem__(self, *args, **kwargs): # real signature unknown""" Return self[key]. """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __ge__(self, *args, **kwargs): # real signature unknown""" Return self>=value. """passdef __gt__(self, *args, **kwargs): # real signature unknown""" Return self>value. """passdef __hash__(self, *args, **kwargs): # real signature unknown""" Return hash(self). """passdef __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__"""str(object='') -> strstr(bytes_or_buffer[, encoding[, errors]]) -> strCreate a new string object from the given object. If encoding orerrors is specified, then the object must expose a data bufferthat 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'.# (copied from class doc)"""passdef __iter__(self, *args, **kwargs): # real signature unknown""" Implement iter(self). """passdef __len__(self, *args, **kwargs): # real signature unknown""" Return len(self). """passdef __le__(self, *args, **kwargs): # real signature unknown""" Return self<=value. """passdef __lt__(self, *args, **kwargs): # real signature unknown""" Return self<value. """passdef __mod__(self, *args, **kwargs): # real signature unknown""" Return self%value. """passdef __mul__(self, *args, **kwargs): # real signature unknown""" Return self*value.n """pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passdef __ne__(self, *args, **kwargs): # real signature unknown""" Return self!=value. """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passdef __rmod__(self, *args, **kwargs): # real signature unknown""" Return value%self. """passdef __rmul__(self, *args, **kwargs): # real signature unknown""" Return self*value. """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" S.__sizeof__() -> size of S in memory, in bytes """passdef __str__(self, *args, **kwargs): # real signature unknown""" Return str(self). """passclass super(object):"""super() -> same as super(__class__, <first argument>)super(type) -> unbound super objectsuper(type, obj) -> bound super object; requires isinstance(obj, type)super(type, type2) -> bound super object; requires issubclass(type2, type)Typical use to call a cooperative superclass method:class C(B):def meth(self, arg):super().meth(arg)This works for class methods too:class C(B):@classmethoddef cmeth(cls, arg):super().cmeth(arg)"""def __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __get__(self, *args, **kwargs): # real signature unknown""" Return an attribute of instance, which is of type owner. """passdef __init__(self, type1=None, type2=None): # known special case of super.__init__"""super() -> same as super(__class__, <first argument>)super(type) -> unbound super objectsuper(type, obj) -> bound super object; requires isinstance(obj, type)super(type, type2) -> bound super object; requires issubclass(type2, type)Typical use to call a cooperative superclass method:class C(B):def meth(self, arg):super().meth(arg)This works for class methods too:class C(B):@classmethoddef cmeth(cls, arg):super().cmeth(arg)# (copied from class doc)"""pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """pass__self_class__ = property(lambda self: type(object))"""the type of the instance invoking super(); may be None:type: type"""__self__ = property(lambda self: type(object))"""the instance invoking super(); may be None:type: type"""__thisclass__ = property(lambda self: type(object))"""the class invoking super():type: type"""class SyntaxWarning(Warning):""" Base class for warnings about dubious syntax. """def __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passclass SystemError(Exception):"""Internal error in the Python interpreter.Please report this to the Python maintainer, along with the traceback,the Python version, and the hardware/OS platform and version."""def __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passclass SystemExit(BaseException):""" Request to exit from the interpreter. """def __init__(self, *args, **kwargs): # real signature unknownpasscode = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception code"""class TabError(IndentationError):""" Improper mixture of spaces and tabs. """def __init__(self, *args, **kwargs): # real signature unknownpassclass TimeoutError(OSError):""" Timeout expired. """def __init__(self, *args, **kwargs): # real signature unknownpassclass tuple(object):"""tuple() -> empty tupletuple(iterable) -> tuple initialized from iterable's itemsIf the argument is a tuple, the return value is the same object."""def count(self, value): # real signature unknown; restored from __doc__""" T.count(value) -> integer -- return number of occurrences of value """return 0def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__"""T.index(value, [start, [stop]]) -> integer -- return first index of value.Raises ValueError if the value is not present."""return 0def __add__(self, *args, **kwargs): # real signature unknown""" Return self+value. """passdef __contains__(self, *args, **kwargs): # real signature unknown""" Return key in self. """passdef __eq__(self, *args, **kwargs): # real signature unknown""" Return self==value. """passdef __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __getitem__(self, *args, **kwargs): # real signature unknown""" Return self[key]. """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __ge__(self, *args, **kwargs): # real signature unknown""" Return self>=value. """passdef __gt__(self, *args, **kwargs): # real signature unknown""" Return self>value. """passdef __hash__(self, *args, **kwargs): # real signature unknown""" Return hash(self). """passdef __init__(self, seq=()): # known special case of tuple.__init__"""tuple() -> empty tupletuple(iterable) -> tuple initialized from iterable's itemsIf the argument is a tuple, the return value is the same object.# (copied from class doc)"""passdef __iter__(self, *args, **kwargs): # real signature unknown""" Implement iter(self). """passdef __len__(self, *args, **kwargs): # real signature unknown""" Return len(self). """passdef __le__(self, *args, **kwargs): # real signature unknown""" Return self<=value. """passdef __lt__(self, *args, **kwargs): # real signature unknown""" Return self<value. """passdef __mul__(self, *args, **kwargs): # real signature unknown""" Return self*value.n """pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passdef __ne__(self, *args, **kwargs): # real signature unknown""" Return self!=value. """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passdef __rmul__(self, *args, **kwargs): # real signature unknown""" Return self*value. """passclass type(object):"""type(object_or_name, bases, dict)type(object) -> the object's typetype(name, bases, dict) -> a new type"""def mro(self): # real signature unknown; restored from __doc__"""mro() -> listreturn a type's method resolution order"""return []def __call__(self, *args, **kwargs): # real signature unknown""" Call self as a function. """passdef __delattr__(self, *args, **kwargs): # real signature unknown""" Implement delattr(self, name). """passdef __dir__(self): # real signature unknown; restored from __doc__"""__dir__() -> listspecialized __dir__ implementation for types"""return []def __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __init__(cls, what, bases=None, dict=None): # known special case of type.__init__"""type(object_or_name, bases, dict)type(object) -> the object's typetype(name, bases, dict) -> a new type# (copied from class doc)"""passdef __instancecheck__(self): # real signature unknown; restored from __doc__"""__instancecheck__() -> boolcheck if an object is an instance"""return False@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passdef __prepare__(self): # real signature unknown; restored from __doc__"""__prepare__() -> dictused to create the namespace for the class statement"""return {}def __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passdef __setattr__(self, *args, **kwargs): # real signature unknown""" Implement setattr(self, name, value). """passdef __sizeof__(self): # real signature unknown; restored from __doc__"""__sizeof__() -> intreturn memory consumption of the type object"""return 0def __subclasscheck__(self): # real signature unknown; restored from __doc__"""__subclasscheck__() -> boolcheck if a class is a subclass"""return Falsedef __subclasses__(self): # real signature unknown; restored from __doc__""" __subclasses__() -> list of immediate subclasses """return []__abstractmethods__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default__bases__ = (object,)__base__ = object__basicsize__ = 864__dictoffset__ = 264__dict__ = None # (!) real value is ''__flags__ = -2146675712__itemsize__ = 40__mro__ = (None, # (!) forward: type, real value is ''object,)__name__ = 'type'__qualname__ = 'type'__text_signature__ = None__weakrefoffset__ = 368class TypeError(Exception):""" Inappropriate argument type. """def __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passclass UnboundLocalError(NameError):""" Local name referenced but not bound to a value. """def __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passclass ValueError(Exception):""" Inappropriate argument value (of correct type). """def __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passclass UnicodeError(ValueError):""" Unicode related error. """def __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passclass UnicodeDecodeError(UnicodeError):""" Unicode decoding error. """def __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passdef __str__(self, *args, **kwargs): # real signature unknown""" Return str(self). """passencoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception encoding"""end = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception end"""object = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception object"""reason = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception reason"""start = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception start"""class UnicodeEncodeError(UnicodeError):""" Unicode encoding error. """def __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passdef __str__(self, *args, **kwargs): # real signature unknown""" Return str(self). """passencoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception encoding"""end = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception end"""object = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception object"""reason = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception reason"""start = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception start"""class UnicodeTranslateError(UnicodeError):""" Unicode translation error. """def __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passdef __str__(self, *args, **kwargs): # real signature unknown""" Return str(self). """passencoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception encoding"""end = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception end"""object = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception object"""reason = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception reason"""start = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""exception start"""class UnicodeWarning(Warning):"""Base class for warnings about Unicode related problems, mostlyrelated to conversion problems."""def __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passclass UserWarning(Warning):""" Base class for warnings generated by user code. """def __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passclass ZeroDivisionError(ArithmeticError):""" Second argument to a division or modulo operation was zero. """def __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passclass zip(object):"""zip(iter1 [,iter2 [...]]) --> zip objectReturn a zip object whose .__next__() method returns a tuple wherethe i-th element comes from the i-th iterable argument. The .__next__()method continues until the shortest iterable in the argument sequenceis exhausted and then it raises StopIteration."""def __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __init__(self, iter1, iter2=None, *some): # real signature unknown; restored from __doc__passdef __iter__(self, *args, **kwargs): # real signature unknown""" Implement iter(self). """pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passdef __next__(self, *args, **kwargs): # real signature unknown""" Implement next(self). """passdef __reduce__(self, *args, **kwargs): # real signature unknown""" Return state information for pickling. """passclass __loader__(object):"""Meta path import for built-in modules.All methods are either class or static methods to avoid the need toinstantiate the class."""def create_module(self, *args, **kwargs): # real signature unknown""" Create a built-in module """passdef exec_module(self, *args, **kwargs): # real signature unknown""" Exec a built-in module """passdef find_module(self, *args, **kwargs): # real signature unknown"""Find the built-in module.If 'path' is ever specified then the search is considered a failure.This method is deprecated. Use find_spec() instead."""passdef find_spec(self, *args, **kwargs): # real signature unknownpassdef get_code(self, *args, **kwargs): # real signature unknown""" Return None as built-in modules do not have code objects. """passdef get_source(self, *args, **kwargs): # real signature unknown""" Return None as built-in modules do not have source code. """passdef is_package(self, *args, **kwargs): # real signature unknown""" Return False as built-in modules are never packages. """passdef load_module(self, *args, **kwargs): # real signature unknown"""Load the specified module into sys.modules and return it.This method is deprecated. Use loader.exec_module instead."""passdef module_repr(module): # reliably restored by inspect"""Return repr for the module.The method is deprecated. The import machinery does the job itself."""passdef __init__(self, *args, **kwargs): # real signature unknownpass__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default"""list of weak references to the object (if defined)"""__dict__ = None # (!) real value is ''# variables with complex valuesEllipsis = None # (!) real value is ''NotImplemented = None # (!) real value is ''__spec__ = None # (!) real value is ''
str
三.所有字符串數據類型舉例
#變量名字變大寫
tmp = "zhangyanlin"
tmp_new = tmp.upper()
print(tmp_new)# 輸出所有字符定義的所有類型
tmp.upper()
print(dir(tmp))
#['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']#把首字母變成大寫
u1 = "zhang"
u2 = u1.capitalize()
print(u2)#20定義20個位,不夠用_補全。
u1 = "zhang"
u2 = u1.center(20 ,'_')
print(u2)#看zh在前10位出現了幾次
u1 = "zhangyanlin is zhgod"
u2 = u1.count('zh',0, 10)
print(u2)#獲取字符串中大于等于0的位置,小于2的位置
u1 = "zhang"
print(u1.endswith('h',0,2))#將tab轉換成空格
u1 = "zhang\t123"
print(u1.expandtabs(20))#找位數,相同只能找第一個出現的,沒有想應得會反饋-1
u1 = "zhang hello"
print(u1.find('h'))#站位符0和1是代表站位符
u1 = "name {0}, age {1}"
print(u1.format("zhang",18))u1 = " zhang is yan "#判斷是否是字母
print(u1.isalpha())#判斷是否是數字
print(u1.isdigit())#判斷是否是字母和數字
print(u1.isalnum())#判斷是否是小寫
print(u1.islower())#判斷是否是空格
print(u1.isspace())#判斷是不是標題
print(u1.istitle())#判斷是不是全部都是大寫
print(u1.isupper())#把列表里的內容連接一起
print("_".join(u1))#內容左對齊,右側填充
print(u1.ljust(1))#內容變小寫
print(u1.lower())#移除左邊的空格
print(u1.lstrip())#移除右邊的空格
print(u1.rstrip())#把有空格的內容分割,變成元祖類型,從左找;rpartition從右開始分割
print(u1.partition('is'))#替換,后面可以加替換幾個,從左往右
print(u1.replace('zh','ZH'))#找到一個字符分割,從右,split從左分割
print(u1.rsplit('a',1))#是否以某個字符串開始開始
print(u1.startswith('z'))#移除兩邊空格(strip)
print(u1.strip())#大寫變小寫,小寫變大寫
print(u1.swapcase())#變大寫(upper)
print(u1.upper())
四.索引
u1 = "zhangyanlin"
print(u1[0])
print(u1[1])
print(u1[2])
print(u1[3])
print(u1[4])
print(u1[5])
五.切片
#切出zhan,注:0是代表第一位,4代表小于四,知道第三個數
u1 = "zhangyanlin"
print(u1[0:4])
六.循環切片
1.while使用
u1 = "zhangyanlin"
u2 = 0
while u2 < len(u1):print(u1[u2])u2+=1
2.for使用
#循環切片
u1 = "zhangyanlin"
for u2 in u1:print(u2)#循環切片,輸出除了y
u1 ="zhangyanlin"
for u2 in u1:if u2 =="y":continueprint(u2)#循環切片,輸出到y后不執行
u1 ="zhangyanlin"
for u2 in u1:if u2 =="y":breakprint(u2)
字符串格式化
Python的字符串格式化有兩種方式: 百分號方式、format方式
百分號的方式相對來說比較老,而format方式則是比較先進的方式,企圖替換古老的方式,目前兩者并存。[PEP-3101]
This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing ‘%’ string formatting operator.
1、百分號方式
%[(name)][flags][width].[precision]typecode
-
(name) 可選,用于選擇指定的key
-
flags 可選,可供選擇的值有:
- + 右對齊;正數前加正好,負數前加負號;
- - 左對齊;正數前無符號,負數前加負號;
- 空格 右對齊;正數前加空格,負數前加負號;
- 0 右對齊;正數前無符號,負數前加負號;用0填充空白處
-
width 可選,占有寬度
-
.precision 可選,小數點后保留的位數
-
typecode 必選
- s,獲取傳入對象的__str__方法的返回值,并將其格式化到指定位置
- r,獲取傳入對象的__repr__方法的返回值,并將其格式化到指定位置
- c,整數:將數字轉換成其unicode對應的值,10進制范圍為 0 <= i <= 1114111(py27則只支持0-255);字符:將字符添加到指定位置
- o,將整數轉換成 八 進制表示,并將其格式化到指定位置
- x,將整數轉換成十六進制表示,并將其格式化到指定位置
- d,將整數、浮點數轉換成 十 進制表示,并將其格式化到指定位置
- e,將整數、浮點數轉換成科學計數法,并將其格式化到指定位置(小寫e)
- E,將整數、浮點數轉換成科學計數法,并將其格式化到指定位置(大寫E)
- f, 將整數、浮點數轉換成浮點數表示,并將其格式化到指定位置(默認保留小數點后6位)
- F,同上
- g,自動調整將整數、浮點數轉換成 浮點型或科學計數法表示(超過6位數用科學計數法),并將其格式化到指定位置(如果是科學計數則是e;)
- G,自動調整將整數、浮點數轉換成 浮點型或科學計數法表示(超過6位數用科學計數法),并將其格式化到指定位置(如果是科學計數則是E;)
- %,當字符串中存在格式化標志時,需要用 %%表示一個百分號
注:Python中百分號格式化是不存在自動將整數轉換成二進制表示的方式
常用格式化:
tpl = "i am %s" % "alex"tpl = "i am %s age %d" % ("alex", 18)tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18}tpl = "percent %.2f" % 99.97623tpl = "i am %(pp).2f" % {"pp": 123.425556, }tpl = "i am %.2f %%" % {"pp": 123.425556, }
2、Format方式
[[fill]align][sign][#][0][width][,][.precision][type]
- fill 【可選】空白處填充的字符
- align 【可選】對齊方式(需配合width使用)
- < ,內容左對齊
- > ,內容右對齊(默認)
- =,內容右對齊,將符號放置在填充字符的左側,且只對數字類型有效。 即使:符號+填充物+數字
- ^,內容居中
- sign 【可選】有無符號數字
- +,正號加正,負號加負;
- -,正號不變,負號加負;
- 空格 ,正號空格,負號加負;
-
【可選】對于二進制、八進制、十六進制,如果加上#,會顯示 0b/0o/0x,否則不顯示
- , 【可選】為數字添加分隔符,如:1,000,000
- width 【可選】格式化位所占寬度
- .precision 【可選】小數位保留精度
- type 【可選】格式化類型
- 傳入” 字符串類型 “的參數
- s,格式化字符串類型數據
- 空白,未指定類型,則默認是None,同s
- _傳入“ 整數類型 ”的參數
_- b,將10進制整數自動轉換成2進制表示然后格式化
- c,將10進制整數自動轉換為其對應的unicode字符
- d,十進制整數
- o,將10進制整數自動轉換成8進制表示然后格式化;
- x,將10進制整數自動轉換成16進制表示然后格式化(小寫x)
- X,將10進制整數自動轉換成16進制表示然后格式化(大寫X)
- 傳入“ 浮點型或小數類型 ”的參數
- e, 轉換為科學計數法(小寫e)表示,然后格式化;
- E, 轉換為科學計數法(大寫E)表示,然后格式化;
- f , 轉換為浮點型(默認小數點后保留6位)表示,然后格式化;
- F, 轉換為浮點型(默認小數點后保留6位)表示,然后格式化;
- g, 自動在e和f中切換
- G, 自動在E和F中切換
- %,顯示百分比(默認顯示小數點后6位)
- 傳入” 字符串類型 “的參數
常用格式化:
tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])tpl = "i am {0}, age {1}, really {0}".format("seven", 18)tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)tpl = "i am {:s}, age {:d}".format(*["seven", 18])tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)