首页 技术 正文
技术 2022年11月17日
0 收藏 769 点赞 2,962 浏览 26488 个字
Python全栈开发【基础二】

本节内容:

  • Python 运算符(算术运算、比较运算、赋值运算、逻辑运算、成员运算)
  • 基本数据类型(数字、布尔值、字符串、列表、元组、字典)
  • 其他(编码,range,for,while)
Python 运算符

1、算术运算:

2、比较运算:

3、赋值运算:

4、逻辑运算:

 5、成员运算:

基本数据类型

1、数字

int(整型)

 数字  int ,所有的功能,都放在int里 a1 = a1 =  - int     将字符串转换为数字     a = "     print(type(a),a)     b = int(a)     print(type(b),b)     进制转换,例子为转换为16进制     num = "     v = )     print(v) - bit_lenght     当前数字的二进制,至少用n位表示     r = age.bit_length()

int常用属性

 class int(object):     """     int(x=0) -> integer     int(x, base=10) -> integer     Convert a number or string to an integer, or return 0 if no arguments     are given.  If x is a number, return x.__int__().  For floating point     numbers, this truncates towards zero.     If x is not a number or if base is given, then x must be a string,     bytes, or bytearray instance representing an integer literal in the     given base.  The literal can be preceded by '+' or '-' and be surrounded     by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.     Base 0 means to interpret the base from the string as an integer literal.     >>> int('0b100', base=0)     """     def bit_length(self): # real signature unknown; restored from __doc__         """         int.bit_length() -> int         Number of bits necessary to represent self in binary.         """         """         表示该数字返回时占用的最少位数         >>> (951).bit_length()         """         return 0     def conjugate(self, *args, **kwargs): # real signature unknown         """ Returns self, the complex conjugate of any int."""         """         返回该复数的共轭复数         #返回复数的共轭复数         >>> (95 + 11j).conjugate()         (95-11j)         #返回复数的实数部分         >>> (95 + 11j).real         95.0         #返回复数的虚数部分         >>> (95 + 11j).imag         11.0         """         pass     @classmethod # known case     def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__         """         int.from_bytes(bytes, byteorder, *, signed=False) -> int         Return the integer represented by the given array of bytes.         The bytes argument must be a bytes-like object (e.g. bytes or bytearray).         The byteorder argument determines the byte order used to represent the         integer.  If byteorder is 'big', the most significant byte is at the         beginning of the byte array.  If byteorder is 'little', the most         significant byte is at the end of the byte array.  To request the native         byte order of the host system, use `sys.byteorder' as the byte order value.         The signed keyword-only argument indicates whether two's complement is         used to represent the integer.         """         """         这个方法是在Python3.2的时候加入的,python官方给出了下面几个例子:         >>> int.from_bytes(b'\x00\x10', byteorder='big')         >>> int.from_bytes(b'\x00\x10', byteorder='little')         >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)         -1024         >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)         >>> int.from_bytes([255, 0, 0], byteorder='big')         """         pass     def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__         """         int.to_bytes(length, byteorder, *, signed=False) -> bytes         Return an array of bytes representing an integer.         The integer is represented using length bytes.  An OverflowError is         raised if the integer is not representable with the given number of         bytes.         The byteorder argument determines the byte order used to represent the         integer.  If byteorder is 'big', the most significant byte is at the         beginning of the byte array.  If byteorder is 'little', the most         significant byte is at the end of the byte array.  To request the native         byte order of the host system, use `sys.byteorder' as the byte order value.         The signed keyword-only argument determines whether two's complement is         used to represent the integer.  If signed is False and a negative integer         is given, an OverflowError is raised.         """         """         python官方给出了下面几个例子:         >>> (1024).to_bytes(2, byteorder='big')         b'\x04\x00'         >>> (1024).to_bytes(10, byteorder='big')         b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'         >>> (-1024).to_bytes(10, byteorder='big', signed=True)         b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'         >>> x = 1000         >>> x.to_bytes((x.bit_length() // 8) + 1, byteorder='little')         b'\xe8\x03'         """         pass     def __abs__(self, *args, **kwargs): # real signature unknown         """ abs(self)"""         """         返回一个绝对值         >>> (95).__abs__()         -95         >>> (-95).__abs__()         """         pass     def __add__(self, *args, **kwargs): # real signature unknown         """ Return self+value."""         """         加法,也可区分数字和字符串         >>> (95).__add__(1)         >>> (95).__add__("1")         NotImplemented         >>>         """         pass     def __and__(self, *args, **kwargs): # real signature unknown         """ Return self&value."""         pass     def __bool__(self, *args, **kwargs): # real signature unknown         """ self != 0 """         """         判断一个整数对象是否为0,如果为0,则返回False,如果不为0,则返回True         >>> (95).__bool__()         True         >>> (0).__bool__()         False         """         pass     def __ceil__(self, *args, **kwargs): # real signature unknown         """ Ceiling of an Integral returns itself. """         pass     def __divmod__(self, *args, **kwargs): # real signature unknown         """ Return divmod(self, value). """         """         返回一个元组,第一个元素为商,第二个元素为余数         >>> (9).__divmod__(5)         (1, 4)         """         pass     def __eq__(self, *args, **kwargs): # real signature unknown         """ Return self==value. """         """         判断两个值是否相等         >>> (95).__eq__(95)         True         >>> (95).__eq__(9)         False         """         pass     def __float__(self, *args, **kwargs): # real signature unknown         """ float(self) """         """         将一个整数转换成浮点型         >>> (95).__float__()         95.0         """         pass     def __floordiv__(self, *args, **kwargs): # real signature unknown         """ Return self//value. """         """         整除,保留结果的整数部分         >>> (95).__floordiv__(9)         """         pass     def __floor__(self, *args, **kwargs): # real signature unknown         """ Flooring an Integral returns itself. """         """         返回本身         >>> (95).__floor__()         """         pass     def __format__(self, *args, **kwargs): # real signature unknown         """         转换对象的类型         >>> (95).__format__('f')         '95.000000'         >>> (95).__format__('b')         '1011111'         """         pass     def __getattribute__(self, *args, **kwargs): # real signature unknown         """ Return getattr(self, name). """         """         判断这个类中是否包含这个属性,如果包含则打印出值,如果不包含,就报错了         >>> (95).__getattribute__('__abs__')         <method-wrapper '__abs__' of int object at 0x9f93c0>         >>> (95).__getattribute__('__aaa__')         Traceback (most recent call last):         File "<stdin>", line 1, in <module>         AttributeError: 'int' object has no attribute '__aaa__'         """         pass     def __getnewargs__(self, *args, **kwargs): # real signature unknown         pass     def __ge__(self, *args, **kwargs): # real signature unknown         """ Return self>=value. """         """         判断是否大于等于         >>> (95).__ge__(9)         True         >>> (95).__ge__(99)         False         """         pass     def __gt__(self, *args, **kwargs): # real signature unknown         """ Return self>value. """         """         判断是否大于         >>> (95).__gt__(9)         True         >>> (95).__gt__(99)         False         """         pass     def __hash__(self, *args, **kwargs): # real signature unknown         """ Return hash(self). """         """         计算哈希值,整数返回本身         >>> (95).__hash__()         >>> (95.95).__hash__()         """         pass     def __index__(self, *args, **kwargs): # real signature unknown         """ Return self converted to an integer, if self is suitable for use as an index into a list. """         pass     def __init__(self, x, base=10): # known special case of int.__init__         """          这个是一个类的初始化方法,当int类被实例化的时候,这个方法默认就会被执行         """         """         int(x=0) -> integer         int(x, base=10) -> integer         Convert a number or string to an integer, or return 0 if no arguments         are given.  If x is a number, return x.__int__().  For floating point         numbers, this truncates towards zero.         If x is not a number or if base is given, then x must be a string,         bytes, or bytearray instance representing an integer literal in the         given base.  The literal can be preceded by '+' or '-' and be surrounded         by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.         Base 0 means to interpret the base from the string as an integer literal.         >>> int('0b100', base=0)         # (copied from class doc)         """         pass     def __int__(self, *args, **kwargs): # real signature unknown         """ int(self) """         """         转换为整型         >>> (9.5).__int__()         """         pass     def __invert__(self, *args, **kwargs): # real signature unknown         """ ~self """         pass     def __le__(self, *args, **kwargs): # real signature unknown         """ Return self<=value. """         """         判断是否小于等于         >>> (95).__le__(99)         True         >>> (95).__le__(9)         False         """         pass     def __lshift__(self, *args, **kwargs): # real signature unknown         """ Return self<<value. """         """         用于二进制位移,这个是向左移动         >>> bin(95)         '0b1011111'         >>> a = (95).__lshift__(2)         >>> bin(a)         '0b101111100'          >>>         """         pass     def __lt__(self, *args, **kwargs): # real signature unknown         """ Return self<value. """         """         判断是否小于         >>> (95).__lt__(9)         False         >>> (95).__lt__(99)         True         """         pass     def __mod__(self, *args, **kwargs): # real signature unknown         """ Return self%value. """         """         取模 %         >>> (95).__mod__(9)         """         pass     def __mul__(self, *args, **kwargs): # real signature unknown         """ Return self*value. """         """         乘法 *         >>> (95).__mul__(10)         """         pass     def __neg__(self, *args, **kwargs): # real signature unknown         """ -self """         """         将正数变为负数,将负数变为正数         >>> (95).__neg__()         -95         >>> (-95).__neg__()         """         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. """         pass     def __ne__(self, *args, **kwargs): # real signature unknown         """ Return self!=value. """         """         不等于         >>> (95).__ne__(9)         True         >>> (95).__ne__(95)         False         """         pass     def __or__(self, *args, **kwargs): # real signature unknown         """ Return self|value. """         """         二进制或的关系,只要有一个为真,就为真         >>> a = 4         >>> b = 0         >>> a.__or__(b)     # a --> 00000100        b --> 00000000         >>> b = 1           # b --> 00000001         >>> a.__or__(b)         """         pass     def __pos__(self, *args, **kwargs): # real signature unknown         """ +self """         pass     def __pow__(self, *args, **kwargs): # real signature unknown         """ Return pow(self, value, mod). """         """         幂         >>> (2).__pow__(10)         """         pass     def __radd__(self, *args, **kwargs): # real signatre unknown         """ Return value+self. """         """         加法,将value放在前面         >>> a.__radd__(b)       # 相当于 b+a         """         pass     def __rand__(self, *args, **kwargs): # real signature unknown         """ Return value&self. """         """         二进制与的关系,两个都为真,才为真,有一个为假,就为假         """         pass     def __rdivmod__(self, *args, **kwargs): # real signature unknown         """ Return divmod(value, self). """         pass     def __repr__(self, *args, **kwargs): # real signature unknown         """ Return repr(self). """         pass     def __rfloordiv__(self, *args, **kwargs): # real signature unknown         """ Return value//self. """         pass     def __rlshift__(self, *args, **kwargs): # real signature unknown         """ Return value<<self. """         pass     def __rmod__(self, *args, **kwargs): # real signature unknown         """ Return value%self. """         pass     def __rmul__(self, *args, **kwargs): # real signature unknown         """ Return value*self. """         pass     def __ror__(self, *args, **kwargs): # real signature unknown         """ Return value|self. """         pass     def __round__(self, *args, **kwargs): # real signature unknown         """         Rounding an Integral returns itself.         Rounding with an ndigits argument also returns an integer.         """         pass     def __rpow__(self, *args, **kwargs): # real signature unknown         """ Return pow(value, self, mod). """         pass     def __rrshift__(self, *args, **kwargs): # real signature unknown         """ Return value>>self. """         pass     def __rshift__(self, *args, **kwargs): # real signature unknown         """ Return self>>value. """         pass     def __rsub__(self, *args, **kwargs): # real signature unknown         """ Return value-self. """         pass     def __rtruediv__(self, *args, **kwargs): # real signature unknown         """ Return value/self. """         pass     def __rxor__(self, *args, **kwargs): # real signature unknown         """ Return value^self. """         pass     def __sizeof__(self, *args, **kwargs): # real signature unknown         """ Returns size in memory, in bytes """         """         在内存中占多少个字节         >>> a = 95         >>> a.__sizeof__()         """         pass     def __str__(self, *args, **kwargs): # real signature unknown         """ Return str(self). """         """         将一个正数转为字符串         >>> a = 95         >>> a = a.__str__()         >>> print(type(a))         <class 'str'>         """         pass     def __sub__(self, *args, **kwargs): # real signature unknown         """ Return self-value. """         """         减法运算         >>> (95).__sub__(5)         """         pass     def __truediv__(self, *args, **kwargs): # real signature unknown         """ Return self/value. """         """         除法运算         >>> (95).__truediv__(5)         19.0         """         pass     def __trunc__(self, *args, **kwargs): # real signature unknown         """ Truncating an Integral returns itself. """         """         返回一个对象的整数部分         >>> (95.95).__trunc__()         """         pass     def __xor__(self, *args, **kwargs): # real signature unknown         """ Return self^value. """         """         将对象与值进行二进制的或运算,一个为真,就为真         >>> a = 4         >>> b = 1         >>> a.__xor__(b)         >>> c = 0         >>> a.__xor__(c)         """         pass     denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default     """ 分母 = 1 """     """the denominator of a rational number in lowest terms"""     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default     """ 虚数 """     """the imaginary part of a complex number"""     numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default     """ 分子 = 数字大小 """     """the numerator of a rational number in lowest terms"""     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default     """ 实属 """     """the real part of a complex number""" int

int

2、布尔值

真或假1 或 0一下情况一般为FalseNone “” () [] {} 0 ==> False其余情况一般为真

3、字符串

 test = "来啊相互伤害啊" # 一、for循环 #     for 变量名 in 字符串: #         变量名 #     break #     continue     index =     while index < len(test):         v = test[index]         print(v)         index +=     print('=======')     for  in test:         print()     test = "来啊相互伤害啊"     for item in test:         print(item)         break     for item in test:         continue         print(item) # 二、索引,下标,获取字符串中的某一个字符     v = test[]     print(v) # 三、切片     v = test[:-] # =<  <     print(v) # 四、获取长度 #     Python3: len获取当前字符串中由几个字符组成     v = len(test)     print(v) # 注意: # len("asdf") # for循环 # 索引 # 切片 # 五、获取连续或不连续的数字,range用法 #     Python2中直接创建在内容中 #     python3中只有for循环时,才一个一个创建     r1 = range()     r2 = range(,)     r3 = range(,,) # 帮助创建连续的数字,通过设置步长来指定不连续     v = range(, , )     for item in v:         print(item)

字符串常用属性

 #!/usr/bin/env python # -*- coding:UTF-8 -*- # Author:Ocean class str(object):     def capitalize(self): # real signature unknown; restored from __doc__         # 首字母变大写         # name = "ocean"         # a = name.capitalize()         #         print(a)     def casefold(self): # real signature unknown; restored from __doc__         #         首字母变小写         # name = "Ocean"         # a =name.casefold()         #         print(a)     def center(self, width, fillchar=None): # real signature unknown; restored from __doc__         # 内容居中,width:总长度;fillchar:空白处填充内容,默认无。         # name = "ocean"         #         a = name.center(60,'$')         #         print(a)     def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__         # 子序列个数,0到12中a出现了几次。         #         name = "ocean is a good man"         #         v= name.count("a",0,12)         #         print(v)     def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__         # 编码,针对unicode.         # temp = "烧饼"         # temp.encode("unicode")     def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__         # 是否以XX结束,0到4是否以n结尾         # name = "ocean is a good man"         # v = name.endswith("n",0,4)         # print(v)     def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__         # 将tab转换成空格,默认一个tab转换成8个空格         # a = n.expandtabs()         # b = n.expandtabs(16)         # print(a)         # print(b)     def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__         # 寻找子序列位置,如果没找到,返回 -1。         # name = "ocean is a good man"         # a = name.find("good")         # print(a)     def format(self, *args, **kwargs): # known special case of str.format          #    字符串格式化,动态参数          # 格式化,传入的值 {"name": 'alex', "a": 19}          # test = 'i am {name}, age {a}'          # v1 = test.format(name='df',a=10)          # v2 = test.format_map({"name": 'alex', "a": 19})  format_map用法(一般用字典键值)     def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__         # 子序列位置,如果没有找到就报错         # name = "ocean is a good man"         # a = name.index("ocean")         # print(a)     def isalnum(self): # real signature unknown; restored from __doc__         # 是否是字母和数字         # name = "ocean is a good man"         # a = name.isalnum()         # print(a)     def isalpha(self): # real signature unknown; restored from __doc__         # 是否是字母         # name = "ocean is a good man"         # a = name.isalpha()         # print(a)     def isdecimal(self): # real signature unknown; restored from __doc__         # 检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。     def isdigit(self): # real signature unknown; restored from __doc__         # 是否是数字         # name = "ocean is a good man"         # a = name.isdigit()         # print(a)     def isidentifier(self): # real signature unknown; restored from __doc__         # 判断字符串是否可为合法的标识符     def islower(self): # real signature unknown; restored from __doc__         # 是否小写         # name = "ocean is A good man"         # a = name.islower()         # print(a)     def isnumeric(self): # real signature unknown; restored from __doc__         # 检查是否只有数字字符组成的字符串         # name = "111111111111111”         # a = name.isnumeric()         # print(a)     def isprintable(self): # real signature unknown; restored from __doc__         # 判断字符串中所有字符是否都属于可见字符         # name = "ocean is a good man"         # a = name.isprintable()         # print(a)     def isspace(self): # real signature unknown; restored from __doc__         # 字符串是否只由空格组成         # name = "  "         # a = name.isspace()         # print(a)     def istitle(self): # real signature unknown; restored from __doc__         # 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写         # name = "Ocean Is A Good Man"         # a = name.istitle()         # print(a)     def isupper(self): # real signature unknown; restored from __doc__         # 检测字符串中所有的字母是否都为大写         # name = "OCEAN"         # a = name.isupper()         # print(a)     def join(self, iterable): # real signature unknown; restored from __doc__         # 连接两个字符串         # li = ["ocean","handsome"]         # a = "".join(li)         # b = "_".join(li)         # print(a)         # print(b)     def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__         # 向左对齐,右侧填充         # name = "ocean is a good man"         # a = name.ljust(60,$)         # print(a)     def lower(self): # real signature unknown; restored from __doc__         # 所有大写变小写         # name = "OCEan"         # a = name.lower()         # print(a)     def lstrip(self, chars=None): # real signature unknown; restored from __doc__         # 移除左侧空白     def maketrans(self, *args, **kwargs): # real signature unknown         # 用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。         # from string import maketrans         # intab = "aeiou"         # outtab = "12345"         # trantab = maketrans(intab, outtab)         # str = "this is string example....wow!!!"         # print(str.translate(trantab))     def partition(self, sep): # real signature unknown; restored from __doc__         # 分割,前,中,后三部分         # name = "ocean is a good man"         # a = name.partition("good")         # print(a)     def replace(self, old, new, count=None): # real signature unknown; restored from __doc__         # 替换         # name = "ocean is a good man"         # a = name.replace("good","man")         # print(a)     def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__         # 返回字符串最后一次出现的位置,如果没有匹配项则返回-1     def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__         # 返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常     def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__         # 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串         # str = "this is string example....wow!!!"         # print(str.rjust(50, '$'))     def rpartition(self, sep): # real signature unknown; restored from __doc__         # 根据指定的分隔符将字符串进行分割     def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__         # 指定分隔符对字符串进行切片         # name = "ocean is a good man"         # a = name.rsplit("is")         # print(a)     def rstrip(self, chars=None): # real signature unknown; restored from __doc__         # 删除 string 字符串末尾的指定字符(默认为空格)     def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__         # 通过指定分隔符对字符串进行切片         # str = "Line1-abcdef \nLine2-abc \nLine4-abcd";         # print str.split( );         # print str.split(' ', 1 );     def splitlines(self, keepends=None): # real signature unknown; restored from __doc__         # 按照行分隔,返回一个包含各行作为元素的列表     def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__         # 检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False     def strip(self, chars=None): # real signature unknown; restored from __doc__         # 用于移除字符串头尾指定的字符(默认为空格).     def swapcase(self): # real signature unknown; restored from __doc__         # 用于对字符串的大小写字母进行转换     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 ""     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 ""     def upper(self): # real signature unknown; restored from __doc__         # 将字符串中的小写字母转为大写字母     def zfill(self, width): # real signature unknown; restored from __doc__         # 返回指定长度的字符串,原字符串右对齐,前面填充0

str

4、列表

 1. 列表格式 # 中括号括起来 # 用 ,分割每个元素 2. 列表中可以嵌套任何类型,列表中的元素可以是 数字,字符串,列表,布尔值..所有的都能放进去 3. 索引取值 print(li[3]) 4. 切片,切片结果也是列表 print(li[3:-1]) 5. 支持for循环、while循环 for item in li:     print(item) # 列表元素,可以被修改 # li = [1, 12, 9, "age", ["aaa", ["19", 10], "bbb"], "alex", True] 6 .索引 # 修改 # li[1] = 120 # print(li) # li[1] = [11,22,33,44] # print(li) 7、删除,索引删除 # del li[1] # print(li) # 切片替换修改 # li[1:3] = [120,90] # print(li) # 切片删除 # del li[2:6] # print(li) 8. in 操作 # li = [1, 12, 9, "age", ["aaa", ["19", 10], "bbb"], "alex", True] # v1 = "aaa" in li # print(v1) # v2 = "age" in li # print(v2) ###### 列表中的元素, 9 .操作 # li = [1, 12, 9, "age", ["aaa", ["19", 10], "bbb"], "alex", True] # li[4][1][0] # [1] # li = [1, 12, 9, "age", ["aaa", ["19", 10], "bbb"], "alex", True] # s = "pouaskdfauspdfiajsdkfj" # s = 123 # a = "123" # int(a) # a = 123 # str(a) 10 转换 # 字符串转换列表   li =  list("asdfasdfasdf"), 内部使用for循环 # s = "pouaskdfauspdfiajsdkfj" # new_li = list(s) # print(new_li) # 列表转换成字符串,  既有数字又有字符串:需要自己写for循环一个一个处理 # li = [11,22,33,"123","alex"] # # r = str(li) # '[11,22,33,"123","alex"]' # # print(r) # s = "" # for i in li: #     s = s + str(i) # print(s) 直接使用字符串join方法:列表中的元素只有字符串 # li = ["123","alex"] # v = "".join(li) # print(v) 补充:字符串创建后,不可修改 # 列表,有序;元素可以被修改

列表常用属性

 # def append(self, p_object): # real signature unknown; restored from __doc__ # 在原来的最后追加 li=[1,2,3,2,34,5] li.append([22,33]) print(li) #结果:[1, 2, 3, 2, 34, 5, [22, 33]] # def clear(self): # real signature unknown; restored from __doc__ # 清空列表 li=[1,2,3,2,34,5] li.clear() print() # def copy(self): # real signature unknown; restored from __doc__ # 复制列表,需赋值 li=[1,2,3,2,34,5] v = li.copy() print(v) # def count(self, value): # real signature unknown; restored from __doc__ # 统计列表中元素的个数 li = [1,2,3,2,34,5] v = li.count(2) print(v) # 结果为2,也就是有两个2 # def extend(self, iterable): # real signature unknown; restored from __doc__ # 扩展列表,参数为可迭代对象(可以for循环的对象)以for循环遍历完结果加入列表 # 注意区别append li = [1,2,3,2,34,5] li.extend(["aa",12,34]) print(li) # def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ # 根据值获取当前索引位置(左边优先) li = [1,2,3,2,34,5] v = li.index(34) print(v) # def insert(self, index, p_object): # real signature unknown; restored from __doc__ # 在指定索引位置插入元素 li = [1,2,3,2,34,5] li.insert(0,[1,2]) print(li) # def pop(self, index=None): # real signature unknown; restored from __doc__ # 删除指定列表索引位置元素,默认删除最后一个,并且获取删除的值 li = [1,2,3,2,34,5] v=li.pop(0) print(li) print(v) # def remove(self, value): # real signature unknown; restored from __doc__ # 删除列表指定值,左边优先(不可获取) li = [1,2,3,2,34,5] li.remove(2) print(li) # def reverse(self): # real signature unknown; restored from __doc__ # 将当前列表反转 li = [1,2,3,2,34,5] li.reverse() print(li) # def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__ # 列表排序(从小到大)可以用反转来reverse()反排序 li = [1,2,3,2,34,5] li.sort() print(li) li.sort(reverse=True) print(li)

list

5、元组(不可修改)

 # 元组,元素不可被修改,不能被增加或者删除 # 1. 书写格式 # tu = (111,"alex",(11,22),[(33,44)],True,33,44,) # 一般写元组的时候,推荐在最后加入 , # 元素不可被修改,不能被增加或者删除 # 2. 索引 # v = tu[0] # print(v) # 3. 切片 # v = tu[0:2] # print(v) # 4. 可以被for循环,可迭代对象 # for item in tu: #     print(item) # 5. 转换 # s = "asdfasdf0" # li = ["asdf","asdfasdf"] # tu = ("asdf","asdf") #遍历字符串,每个字符成为元组元素 # v = tuple(s) # print(v) #字典可以直接转换为元组 # v = tuple(li) # print(v) #元组可以直接转化成列表 # v = list(tu) # print(v) # 如果元组中都为字符串的时候可以用join粘合元组中元素,如果有数字则不可以 # v = "_".join(tu) # print(v) # 列表能够遍历加入列表中 # li = ["asdf","asdfasdf"] # li.extend((11,22,33,)) # print(li) # 6.元组的一级元素不可修改/删除/增加 # tu = (111,"alex",(11,22),[(33,44)],True,33,44,) # # 元组,有序。 # # v = tu[3][0][0] # # print(v) # # v=tu[3] # # print(v) # tu[3][0] = 567 # print(tu)

元组常用属性

 # 由于元组是不可更改的所以只有索引查询跟计数的功能 def count(self, value): # real signature unknown; restored from __doc__ # 获取指定元素在元组中出现的次数 # tu = (,,,) # tu.count() def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ # 获取指定元素在元组中的位置 # tu = (,,,) # tu.index()

tuple

6、set集合

 class set(object): def add(self, *args, **kwargs): # real signature unknown """添加元素 >>> a = {"alex","mm","ocean"} >>> a.add('ss') >>> a {"alex","mm","ocean","ss"} """ def clear(self, *args, **kwargs): # real signature unknown """清除内容 >>> a = {"alex","mm","ocean"} >>> a.clear() >>> a set() """ def copy(self, *args, **kwargs): # real signature unknown """浅拷贝 >>> a = {"alex","mm","ocean"} >>> b = a.copy() >>> b {"alex","mm","ocean"} """ def difference(self, *args, **kwargs): # real signature unknown """A中存在,B中不存在,差集(-) >>> a = {"alex","mm","ocean"} >>> b = {"ll","tt","alex"} >>> a.difference(b) #或者可以为print(a-b) {"mm","ocean"} """ def difference_update(self, *args, **kwargs): # real signature unknown """从当前集合中删除和B中相同的元素,并更新到a中 >>> a = {"alex","mm","ocean"} >>> b = {"ll","tt","alex"} >>> a.difference_update(b) >>> a {"mm","ocean"} """ def discard(self, *args, **kwargs): # real signature unknown """移除指定元素,不存在不报错 >>> a = {"alex","mm","ocean"} >>> a.discard("aa") >>> a """ def intersection(self, *args, **kwargs): # real signature unknown """a与b的交集(&) >>> a = {"alex","mm","ocean"} >>> b = {"ll","tt","alex"} >>> a.intersection(b)  #a&b {"alex"} """ def intersection_update(self, *args, **kwargs): # real signature unknown """取交集并更更新到a中 """ def isdisjoint(self, *args, **kwargs): # real signature unknown """如果没有交集,返回True,否则返回False >>> a = {"alex","mm","ocean"} >>> b = {"ll","tt","alex"} >>> a.isdisjoint(b) False """ def issubset(self, *args, **kwargs): # real signature unknown """是否是子序列 >>> a = {"alex","mm","ocean"} >>> b = {"alex"} >>> b.issubset(a) True >>> a.issubset(b) False """ def issuperset(self, *args, **kwargs): # real signature unknown """是否是父序列 >>> a = {"alex","mm","ocean"} >>> b = {"alex"} >>> a.issuperset(b) True >>> b.issuperset(a) False """ def pop(self, *args, **kwargs): # real signature unknown """移除元素 >>> a = {"alex","mm","ocean"} >>> a.pop() "alex" >>> a {"mm","ocean"} """ def remove(self, *args, **kwargs): # real signature unknown """移除指定元素,不存在报错 >>> a = {"alex","mm","ocean"} >>> a.remove("ss") Traceback (most recent call last):   File , in <module> KeyError: "ss" >>> """ def symmetric_difference(self, *args, **kwargs): # real signature unknown """交叉补集 (^) >>> a = {"alex","mm","ocean"} >>> b = {"ll","tt","alex"} >>> a.symmetric_difference(b)   #a^b {"mm","ocean","ll","tt"} """ def symmetric_difference_update(self, *args, **kwargs): # real signature unknown """交叉补集,并更新到a中 >>> a = {"alex","mm","ocean"} >>> b = {"ll","tt","alex"} >>> a.symmetric_difference_update(b) >>> a {"mm","ocean","ll","tt"} """ def union(self, *args, **kwargs): # real signature unknown """并集,(|) >>> a = {"alex","mm","ocean"} >>> b = {"ll","tt","alex"} >>> a.union(b)  #a|b {"alex","mm","ocean","ll","tt"} """ def update(self, *args, **kwargs): # real signature unknown """更新,添加多个元素,更新  注意区别add >>> a = {"alex","mm","ocean"} >>> b = {"ll","tt","alex"} >>> a.update(b)  #把b中的多个元素加入到a中并更新a中的内容,b并不改变 >>> a {"alex","mm","ocean", "ll","tt"} >>> b {"ll","tt","alex"} """

set

7、字典(无序)

 # 1、基本结构 # info = { #     "k1": "v1", # 键值对 #     "k2": "v2" # } #2、字典的value可以是任何值 # info = { #     "k1": 18, #     "k2": True, #     "k3": [ #         11, #         [], #         (), #         22, #         33, #         { #             'kk1': 'vv1', #             'kk2': 'vv2', #             'kk3': (11,22), #         } #     ], #     "k4": (11,22,33,44) # } # print(info) #3、列表、字典不能作为字典的key # info ={ #     1: 'asdf', #     "k1": 'asdf', #     True: "123", #     # [11,22]: 123 #     (11,22): 123, #     # {'k1':'v1'}: 123 # # } # print(info) # 4 字典无序 # info = { #     "k1": 18, #     "k2": True, #     "k3": [ #         11, #         [], #         (), #         22, #         33, #         { #             'kk1': 'vv1', #             'kk2': 'vv2', #             'kk3': (11,22), #         } #     ], #     "k4": (11,22,33,44) # } # print(info) # 5、索引方式找到指定元素 # info = { #     "k1": 18, #     2: True, #     "k3": [ #         11, #         [], #         (), #         22, #         33, #         { #             'kk1': 'vv1', #             'kk2': 'vv2', #             'kk3': (11,22), #         } #     ], #     "k4": (11,22,33,44) # } # # v = info['k1'] # # print(v) # # v = info[2] # # print(v) # v = info['k3'][5]['kk3'][0] # print(v) # 6 字典支持 del 删除 # info = { #     "k1": 18, #     2: True, #     "k3": [ #         11, #         [], #         (), #         22, #         33, #         { #             'kk1': 'vv1', #             'kk2': 'vv2', #             'kk3': (11,22), #         } #     ], #     "k4": (11,22,33,44) # } # del info['k1'] # # del info['k3'][5]['kk1'] # print(info) # 7 for循环 # dict # info = { #     "k1": 18, #     2: True, #     "k3": [ #         11, #         [], #         (), #         22, #         33, #         { #             'kk1': 'vv1', #             'kk2': 'vv2', #             'kk3': (11,22), #         } #     ], #     "k4": (11,22,33,44) # } # for item in info: #     print(item) # # for item in info.keys(): #     print(item) # for item in info.values(): #     print(item) # for item in info.keys(): #     print(item,info[item]) # for k,v in info.items(): #     print(k,v) # True 1  False 0 # info ={ #     "k1": 'asdf', #     True: "123", #     # [11,22]: 123 #     (11,22): 123, #     # {'k1':' v1'}: 123 # # } # print(info)

字典常用属性

 def clear(self): # real signature unknown; restored from __doc__ # 清空字典 def copy(self): # real signature unknown; restored from __doc__ # 复制字典 @staticmethod # known case def fromkeys(*args, **kwargs): # real signature unknown # 根据序列,创建字典,并指定统一的值 # dic = { #     "k1": 'v1', #     "k2": 'v2' # } # v = dict.fromkeys("k1",123) # print(v) def get(self, k, d=None): # real signature unknown; restored from __doc__ # 根据Key获取值,key不存在时,可以指定默认值(None) # v = dic['k1'] # print(v) # v = dic.get('k11',111111) # print(v) def items(self): # real signature unknown; restored from __doc__ # 可以利用for来遍历键值对 # dic = { #     "k1": 'v1', #     "k2": 'v2' # } # for k,v in dic.items(): #     print(k,v) def keys(self): # real signature unknown; restored from __doc__ # 字典的key # dic = { #     "k1": 'v1', #     "k2": 'v2' # } # for k in dic.keys(): #     print(k) def pop(self, k, d=None): # real signature unknown; restored from __doc__ # 删除并获取值 # dic = { #     "k1": 'v1', #     "k2": 'v2' # } # v = dic.pop('k1',90) # print(dic,v) def popitem(self): # real signature unknown; restored from __doc__ # 删除键值对然后可以获取删除的键值对 # dic = { #     "k1": 'v1', #     "k2": 'v2' # } # k,v = dic.popitem() # print(dic,k,v) def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ # 设置值, # 已存在,不设置,获取当前key对应的值 # 不存在,设置添加,获取当前key对应的值 # dic = { #     "k1": 'v1', #     "k2": 'v2' # } # v = dic.setdefault('k1111','123') # print(dic,v) def update(self, E=None, **F): # known special case of dict.update # 更新 # dic = { #     "k1": 'v1', #     "k2": 'v2' # } # dic.update({'k1': '111111','k3': 123}) #形式一 # print(dic) # dic.update(k1=123,k3=345,k5="asdf")  #形式二 # print(dic) def values(self): # real signature unknown; restored from __doc__ # 字典的值values # dic = { #     "k1": 'v1', #     "k2": 'v2' # } # for v in dic.values(): #     print(v)

dict

 其他

 

1、编码与进制转换

  • utf-8与gbk编码转换,python3里默认的编码方式为unicode

2、range

 #python 2.7 版本 print range(, ) # 结果:[, , , , , , , , ] print range(, , ) # 结果:[, , , , ] print range(, , -) # 结果:[, , , , , , , , , , , , , , ] #python 3.5 版本 a = range() print(a) #结果:range(, )

3、for循环

用户按照顺序循环可迭代对象中的内容

 name = ('ocean','alex') for i in name:     print(i)

4、while循环

 while 条件:         ....     print('...')     补充:         a. while else         b. continue   break            continue ,终止当前循环,开始下一次循环            break    ,终止所有循环 ******continue 是跳出本次循环,break是跳出整个循环(当前的while or for循环)! ****** 用户登陆(三次机会重试) count = :     user = input('>>>')     pwd = input('>>>')     ':         print('欢迎登陆')         print('..........')         break     else:         print('用户名或者密码错误')     count = count + 
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,489
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,904
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,490
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,291