Python全栈开发之2、数据类型-数值、字符串、列表、字典、元组和文件处理
一、Python 运算符
1、算术运算:
2、比较运算:
3、赋值运算:
4、逻辑运算:
5、成员运算:
二、基本数据类型
1、数字整型
int(整型)
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
- #返回表示该数字的时占用的最少位数
- >>> (951).bit_length()
- 10
- #返回绝对值
- >>> (95).__abs__()
- 95
- >>> (-95).__abs__()
- 95
- #用来区分数字和字符串的
- >>> (95).__add__(1)
- 96
- >>> (95).__add__("")
- NotImplemented
- #判断一个整数对象是否为0,如果为0,则返回False,如果不为0,则返回True
- >>> (95).__bool__()
- True
- >>> (0).__bool__()
- False
- #判断两个值是否相等
- >>> (95).__eq__(95)
- True
- >>> (95).__eq__(9)
- False
- #判断是否不等于
- >>> (95).__ne__(9)
- True
- >>> (95).__ne__(95)
- False
- #判断是否大于等于
- >>> (95).__ge__(9)
- True
- >>> (95).__ge__(99)
- False
- #判断是否大于
- >>> (95).__gt__(9)
- True
- >>> (95).__gt__(99)
- False
- #判断是否小于等于
- >>> (95).__le__(99)
- True
- >>> (95).__le__(9)
- False
- #判断是否小于
- >>> (95).__lt__(9)
- False
- >>> (95).__lt__(99)
- True
- #加法运算
- >>> (95).__add__(5)
- 100
- #减法运算
- >>> (95).__sub__(5)
- 90
- #乘法运算
- >>> (95).__mul__(10)
- 950
- #除法运算
- >>> (95).__truediv__(5)
- 19.0
- #取模运算
- >>> (95).__mod__(9)
- 5
- #幂运算
- >>> (2).__pow__(10)
- 1024
- #整除,保留结果的整数部分
- >>> (95).__floordiv__(9)
- >>>
- #转换为整型
- >>> (9.5).__int__()
- 9
- #返回一个对象的整数部分
- >>> (9.5).__trunc__()
- 9
- #将正数变为负数,将负数变为正数
- >>> (95).__neg__()
- -95
- >>> (-95).__neg__()
- 95
- #将一个正数转为字符串
- >>> a = 95
- >>> a = a.__str__()
- >>> print(type(a))
- <class 'str'>
- #将一个整数转换成浮点型
- >>> (95).__float__()
- 95.0
- #转换对象的类型
- >>> (95).__format__('f')
- '95.000000'
- >>> (95).__format__('b')
- ''
- #在内存中占多少个字节
- >>> a = 95
- >>> a.__sizeof__()
- 28
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()
- 10
- """
- 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__()
- 95
- """
- pass
- def __add__(self, *args, **kwargs): # real signature unknown
- """ Return self+value."""
- """
- 加法,也可区分数字和字符串
- >>> (95).__add__(1)
- 96
- >>> (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)
- 10
- """
- pass
- def __floor__(self, *args, **kwargs): # real signature unknown
- """ Flooring an Integral returns itself. """
- """
- 返回本身
- >>> (95).__floor__()
- 95
- """
- 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.95).__hash__()
- 2190550858753015903
- """
- 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__()
- 9
- """
- 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__()
- 95
- """
- 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)
- 1024
- """
- 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__()
- 28
- """
- 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)
- 90
- """
- 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__()
- 95
- """
- 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
2、字符串
"hello world"
str(字符串类型)
万恶的字符串拼接:
字符串一旦创建不可修改,一旦修改或者拼接,都会重新生成字符串
- #切片
- #索引,从0号索引开始,获取字符串中的某一个字符
- string="allen中文"
- print(string[0])
- #索引范围
- print(string[0:2])
- #获取最后一个索引位置
- print(string[-1])
- print(string[0:-1])
- #输出: alle
- #len()获取字符串长度
- len(string)
- print("_".join(string))
- #列子
- index=0
- while index<len(string):
- print(string[index])
- index+=1
- #字符串替换
- new_string=string.replace('en','EN')
- print(new_string)
- #输出: allEN中文
切片
- #查看类型
- age=18
- my_name="obama"
- print(type(age))
- print(type(my_name))
- #输出 :
- # <class 'int'>
- # <class 'str'>
- #将字符串转换为整型
- number=""
- num= int(number)
- print(type(num),num)
- #输出: <class 'int'> 123
- #首字母转换为大写,其他字母都是小写
- name ='my name is AllEn'
- print(name.capitalize())
- # 输出:My name is allen
- #所有字符转换为小写,比lower()更牛逼
- print(name.casefold())
- # 输出:my name is allen
- #统计m出现次数
- print(name.count("m"))
- # 输出:2
- #把name变量放在50个字符中间,设置宽度并把内容居中
- print(name.center(50,'-'))
- # 输出:-----------------my name is AllEn-----------------
- #判断一个字符串是否以en结尾
- print(name.endswith('En'))
- # 输出:True
- #判断一个字符串是否以my开始
- print(name.startswith('my'))
- # 输出:True
- #查找子序列name,找到返回其索引,找不到返回-1
- print(name.find('name'))
- # 输出:3
- #字符串切片
- print(name[name.find('name'):])
- # 输出:name is AllEn
- #format格式化用法1: 将字符串占位符替换为指定的值
- name_info='my name is {_name} and I am {_age} old'
- #
- #
- print(name_info.format(_name='allen',_age=18))
- # 输出:my name is allen and I am 18 old
- #format格式化用法2:根据顺序替换
- name_info1='my name is {0} and I am {1} old'
- print(name_info1.format('allen',18))
- # 输出:my name is allen and I am 18 old
- #format_map 字典用法
- print(name_info.format_map({'_name':'allen','_age':20}))
- # 输出:my name is allen and I am 20 old
- #查找索引,如果找不到会报错
- print(name.index('name'))
- # 输出:3
- #判断是否包含数字和字母
- print('9aA'.isalnum())
- # 输出:True
- #判断是否包含纯英文字符
- print('abA'.isalpha())
- # 输出:True
- # 判断是否是整数
- print(''.isdigit())
- # 输出:True
- #判断是否是数字,支持unicode
- test="二"
- print(test.isnumeric(),test)
- # 输出:True
- #判断是不是合法的变量名
- print('1A'.isidentifier())
- # 输出:False
- #判断是否是小写
- print('abc'.islower())
- # 输出:True
- #判断是否是大写
- print('33a'.isupper())
- # 输出:False
- # 大小写互换
- print('AllEN'.swapcase())
- # 输出:aLLen
- #字符串替换,只替换一次
- print('AlLeN'.replace('l','L',1))
- # 输出:ALLeN
- #join连接两个字符串
- li = ["nick","serven"]
- a = "".join(li)
- b = "_".join(li)
- print(a)
- print(b)
- #输出:nickserven
- # nick_serven
- #大写变小写
- print('ALLen'.lower())
- # 输出:allen
- # 小写变大写
- print('allen'.upper())
- # 输出:ALLEN
- #去掉左右的空格(包括换行符和制表符)
- print(' all\ne\tn '.strip())
- # 输出:allen
- #去掉左边空行和回车
- print(' allen '.lstrip())
- # 输出:allen
- #去掉右边空行和回车
- print(' allen '.rstrip())
- # 输出: allen
- #找到最右边目标的索引
- print('allenlaen'.rfind('a'))
- # 输出:6
- #判断是否全部是空格
- test=" "
- print(test.isspace())
- # 输出:True
- #判断是否是标题(首字母全部是大写)
- title="Return the highest index in S where substring sub"
- print(title.istitle(),title)
- # 输出:False
- # 转换为首字母全部为大写(转换为标题)
- print(title.title())
- # 输出:Return The Highest Index In S Where Substring Sub
- #字符串切割 以t切分 t没有了
- print('allen test'.split('t'))
- # 输出:['allen ', 'es', '']
- #字符串切割 以t切分,只分割一次
- print('allen test'.split('t',1))
- # 输出:['allen ', 'est']
- #只根据换行符分割
- print("asdsad\nasdsad\nasda".splitlines())
- #输出:['asdsad', 'asdsad', 'asda']
- #表示长度50 不够右边*号填充
- print(name.ljust(50,'*'))
- # 输出:my name is AllEn**********************************
- # 表示长度50 不够左边-号填充
- print(name.rjust(50,'-'))
- # 输出:----------------------------------my name is AllEn
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): # real signature unknown; restored from __doc__
- """
- S.capitalize() -> str
- Return a capitalized version of S, i.e. make the first character
- have upper case and the rest lower case.
- """
- return ""
- def casefold(self): # real signature unknown; restored from __doc__
- """
- S.casefold() -> str
- Return a version of S suitable for caseless comparisons.
- """
- return ""
- def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
- """
- S.center(width[, fillchar]) -> str
- Return S centered in a string of length width. Padding is
- done using the specified fill character (default is a space)
- """
- return ""
- 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, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
- """
- S.encode(encoding='utf-8', errors='strict') -> bytes
- Encode S using the codec registered for encoding. Default encoding
- is 'utf-8'. errors may be given to set a different error
- handling scheme. Default is 'strict' meaning that encoding errors raise
- a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
- 'xmlcharrefreplace' as well as any other name registered with
- codecs.register_error that can handle UnicodeEncodeErrors.
- """
- return b""
- def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
- """
- S.endswith(suffix[, start[, end]]) -> bool
- Return True if S ends with the specified suffix, False otherwise.
- With optional start, test S beginning at that position.
- With optional end, stop comparing S at that position.
- suffix can also be a tuple of strings to try.
- """
- return False
- def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
- """
- S.expandtabs(tabsize=8) -> str
- Return a copy of S where all tab characters are expanded using spaces.
- If tabsize is not given, a tab size of 8 characters is assumed.
- """
- return ""
- def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
- """
- 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 format(self, *args, **kwargs): # known special case of str.format
- """
- S.format(*args, **kwargs) -> str
- Return a formatted version of S, using substitutions from args and kwargs.
- The substitutions are identified by braces ('{' and '}').
- """
- pass
- def format_map(self, mapping): # real signature unknown; restored from __doc__
- """
- S.format_map(mapping) -> str
- Return a formatted version of S, using substitutions from mapping.
- The substitutions are identified by braces ('{' and '}').
- """
- return ""
- 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 isalnum(self): # real signature unknown; restored from __doc__
- """
- S.isalnum() -> bool
- Return True if all characters in S are alphanumeric
- and there is at least one character in S, False otherwise.
- """
- return False
- def isalpha(self): # real signature unknown; restored from __doc__
- """
- S.isalpha() -> bool
- Return True if all characters in S are alphabetic
- and there is at least one character in S, False otherwise.
- """
- return False
- def isdecimal(self): # real signature unknown; restored from __doc__
- """
- S.isdecimal() -> bool
- Return True if there are only decimal characters in S,
- False otherwise.
- """
- return False
- def isdigit(self): # real signature unknown; restored from __doc__
- """
- S.isdigit() -> bool
- Return True if all characters in S are digits
- and there is at least one character in S, False otherwise.
- """
- return False
- def isidentifier(self): # real signature unknown; restored from __doc__
- """
- S.isidentifier() -> bool
- Return True if S is a valid identifier according
- to the language definition.
- Use keyword.iskeyword() to test for reserved identifiers
- such as "def" and "class".
- """
- return False
- def islower(self): # real signature unknown; restored from __doc__
- """
- S.islower() -> bool
- Return True if all cased characters in S are lowercase and there is
- at least one cased character in S, False otherwise.
- """
- return False
- def isnumeric(self): # real signature unknown; restored from __doc__
- """
- S.isnumeric() -> bool
- Return True if there are only numeric characters in S,
- False otherwise.
- """
- return False
- def isprintable(self): # real signature unknown; restored from __doc__
- """
- S.isprintable() -> bool
- Return True if all characters in S are considered
- printable in repr() or S is empty, False otherwise.
- """
- return False
- def isspace(self): # real signature unknown; restored from __doc__
- """
- S.isspace() -> bool
- Return True if all characters in S are whitespace
- and there is at least one character in S, False otherwise.
- """
- return False
- def istitle(self): # real signature unknown; restored from __doc__
- """
- S.istitle() -> bool
- Return True if S is a titlecased string and there is at least one
- character in S, i.e. upper- and titlecase characters may only
- follow uncased characters and lowercase characters only cased ones.
- Return False otherwise.
- """
- return False
- def isupper(self): # real signature unknown; restored from __doc__
- """
- S.isupper() -> bool
- Return True if all cased characters in S are uppercase and there is
- at least one cased character in S, False otherwise.
- """
- return False
- def join(self, iterable): # real signature unknown; restored from __doc__
- """
- S.join(iterable) -> str
- Return a string which is the concatenation of the strings in the
- iterable. The separator between elements is S.
- """
- return ""
- def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
- """
- S.ljust(width[, fillchar]) -> str
- Return S left-justified in a Unicode string of length width. Padding is
- done using the specified fill character (default is a space).
- """
- return ""
- def lower(self): # real signature unknown; restored from __doc__
- """
- S.lower() -> str
- Return a copy of the string S converted to lowercase.
- """
- return ""
- def lstrip(self, chars=None): # real signature unknown; restored from __doc__
- """
- S.lstrip([chars]) -> str
- Return a copy of the string S with leading whitespace removed.
- If chars is given and not None, remove characters in chars instead.
- """
- return ""
- def maketrans(self, *args, **kwargs): # real signature unknown
- """
- Return a translation table usable for str.translate().
- If there is only one argument, it must be a dictionary mapping Unicode
- ordinals (integers) or characters to Unicode ordinals, strings or None.
- Character keys will be then converted to ordinals.
- If there are two arguments, they must be strings of equal length, and
- in the resulting dictionary, each character in x will be mapped to the
- character at the same position in y. If there is a third argument, it
- must be a string, whose characters will be mapped to None in the result.
- """
- pass
- 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 not
- found, return S and two empty strings.
- """
- pass
- def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
- """
- S.replace(old, new[, count]) -> str
- Return a copy of S with all occurrences of substring
- old replaced by new. If the optional argument count is
- given, only the first count occurrences are replaced.
- """
- return ""
- def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
- """
- S.rfind(sub[, start[, end]]) -> int
- Return the highest index in S where substring sub is found,
- such that sub is contained within S[start:end]. Optional
- arguments start and end are interpreted as in slice notation.
- Return -1 on failure.
- """
- return 0
- 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 rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
- """
- S.rjust(width[, fillchar]) -> str
- Return S right-justified in a string of length width. Padding is
- done using the specified fill character (default is a space).
- """
- return ""
- def rpartition(self, sep): # real signature unknown; restored from __doc__
- """
- S.rpartition(sep) -> (head, sep, tail)
- Search for the separator sep in S, starting at the end of S, and return
- the part before it, the separator itself, and the part after it. If the
- separator is not found, return two empty strings and S.
- """
- pass
- def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
- """
- S.rsplit(sep=None, maxsplit=-1) -> list of strings
- Return a list of the words in S, using sep as the
- delimiter string, starting at the end of the string and
- working to the front. If maxsplit is given, at most maxsplit
- splits are done. If sep is not specified, any whitespace string
- is a separator.
- """
- return []
- def rstrip(self, chars=None): # real signature unknown; restored from __doc__
- """
- S.rstrip([chars]) -> str
- Return a copy of the string S with trailing whitespace removed.
- If chars is given and not None, remove characters in chars instead.
- """
- return ""
- def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
- """
- S.split(sep=None, maxsplit=-1) -> list of strings
- Return a list of the words in S, using sep as the
- delimiter string. If maxsplit is given, at most maxsplit
- splits are done. If sep is not specified or is None, any
- whitespace string is a separator and empty strings are
- removed from the result.
- """
- return []
- def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
- """
- S.splitlines([keepends]) -> list of strings
- Return a list of the lines in S, breaking at line boundaries.
- Line breaks are not included in the resulting list unless keepends
- is given and true.
- """
- return []
- def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
- """
- S.startswith(prefix[, start[, end]]) -> bool
- Return True if S starts with the specified prefix, False otherwise.
- With optional start, test S beginning at that position.
- With optional end, stop comparing S at that position.
- prefix can also be a tuple of strings to try.
- """
- return False
- def strip(self, chars=None): # real signature unknown; restored from __doc__
- """
- S.strip([chars]) -> str
- Return a copy of the string S with leading and trailing
- whitespace removed.
- If chars is given and not None, remove characters in chars instead.
- """
- return ""
- def swapcase(self): # real signature unknown; restored from __doc__
- """
- S.swapcase() -> str
- Return a copy of S with uppercase characters converted to lowercase
- and vice versa.
- """
- return ""
- 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__
- """
- S.upper() -> str
- Return a copy of S converted to uppercase.
- """
- return ""
- def zfill(self, width): # real signature unknown; restored from __doc__
- """
- S.zfill(width) -> str
- Pad a numeric string S with zeros on the left, to fill a field
- of the specified width. The string S is never truncated.
- """
- return ""
str
- #range创建连续的数字
- for item in range(0,100):
- print(item)
- #设置步长
- for item in range(0,100,2):
- print(item)
range
- # -*- coding:utf-8 -*-
- # Author:sunhao
- name=input('username:')
- age=int(input('age:'))
- job=input('job:')
- salary=int(input('salary:'))
- info='''
- --------info of %s----------
- Name:%s
- Age:%d
- Job:%s
- Salary:%d
- '''%(name,name,age,job,salary) #第一种表示方法
- info2='''
- --------info of {_name}----------
- Name:{_name}
- Age:{_age}
- Job:{_job}
- Salary:{_salary}
- '''.format(_name=name,
- _age=age,
- _job=job,
- _salary=salary) #第二种表示方法 .format()
- info3='''
- --------info of {0}----------
- Name:{0}
- Age:{1}
- Job:{2}
- Salary:{3}
- '''.format(name,
- age,
- job,
- salary) #第三种表示方法
- print(info1)
- print(info2)
- print(info3)
- #三种显示结果是一样的
format()使用方法
3、列表
通过list类创建的对象
names=['Lily','Tom','Lucy','Hanmeimei']
通过下标访问列表中的元素,下标从0开始:
- In[3]: names = ['Lily', 'Tom', 'Lucy', 'Hanmeimei']
- In[4]: names[0]
- Out[4]: 'Lily'
- In[5]: names[1]
- Out[5]: 'Tom'
- In[6]: names[-1]
- Out[6]: 'Hanmeimei'
- In[7]: names[-2]
- Out[7]: 'Lucy'
- >>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
- >>> names[1:4] #取下标1至下标4之间的数字,包括1,不包括4
- ['Tenglan', 'Eric', 'Rain']
- >>> names[1:-1] #取下标1至-1的值,不包括-1
- ['Tenglan', 'Eric', 'Rain', 'Tom']
- >>> names[0:3]
- ['Alex', 'Tenglan', 'Eric']
- >>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样
- ['Alex', 'Tenglan', 'Eric']
- >>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写
- ['Rain', 'Tom', 'Amy']
- >>> names[3:-1] #这样-1就不会被包含了
- ['Rain', 'Tom']
- >>> names[0::2] #后面的2是代表,每隔一个元素,就取一个
- ['Alex', 'Eric', 'Tom']
- >>> names[::2] #和上句效果一样
- ['Alex', 'Eric', 'Tom']
切片
- list.append() #列表追加元素 只是追加在列表的尾部
- list1=['apple','orange','peach','watermelon']
- list1.append('banana') #往列表中添加一个元素
- print (list1)
- ['apple', 'orange', 'peach', 'watermelon', 'banana']
追加元素
- 不能批量插入
- list.insert(index, object) #往列表中插入一个元素
- 例如:
- list1=['apple','orange','peach','watermelon']
- list1.insert(1,'Lemon') #在列表第一个位置插入Lemon这个元素
- print (list1)
- ['apple', 'Lemon', 'orange', 'peach', 'watermelon', 'banana']
insert插入元素
- list1=['apple','orange','peach','watermelon']
- list1[2]='fruit' #把peach修改为fruit
- print(list1)
- 输出:
- ['apple', 'Lemon', 'fruit', 'peach', 'watermelon', 'banana'] #peach被修改为 fruit
修改
- 删除有两种方法:
- 第一种 list.remove()
- list1=['apple', 'Lemon', 'orange', 'peach', 'watermelon', 'banana']
- list1.remove('apple') #remove方法
- 输出:
- print (list1)
- ['Lemon', 'fruit', 'peach', 'watermelon', 'banana']
- 第二种 按下标方法删除
- del list1[1] #删除列表中第1个元素
remove删除
- list.pop() # 默认是从列表中一次弹出最后一个元素
- list.pop(1) # 如果输入下标 等于 del list1[1] 方法
pop弹出元素
- list.index() #查找元素的位置
- list1=['Lemon', 'fruit', 'peach', 'watermelon', 'banana']
- list1.index('peach') #查找peach的位置
- 输出:2 #索引的位置为2
- print(list1[list1.index('peach')])
- 输出:peach
index索引查找元素的位置
- 如果一个列表中有重复的元素,需要统计重复元素的个数
- list.count()
- 例如:
- list1=['banana','peach','watermelon','banana','peach','apple','banana']
- list1.count('banana') #统计列表中banana 的数量
- 输出:
- 3
count统计元素重复个数
- list.clear()
clear清空列表
- list.reverse()
- list1=['banana', 'peach', 'watermelon', 'banana','peach','apple','tomato','banana']
- list1.reverse()
- print (list1)
- ['banana', 'tomato', 'apple', 'peach', 'banana', 'watermelon', 'peach', 'banana'] #元素反转 位置改变
reverse元素反转
- list.sort()
- list1=['banana', 'peach', 'watermelon', 'banana','peach','apple','tomato','banana']
- list1.sort()
- print(list1)
- ['apple', 'banana', 'banana', 'banana', 'peach', 'peach', 'tomato', 'watermelon'] #按照字母排序
sort元素排序
- list.extend()
- #两个列表
- list1=['banana', 'peach', 'watermelon', 'banana','peach','apple','tomato','banana']
- list2=['lily','Lucy','Tom']
- list1.extend(list2) #把list1和list2合并
- print(list1)
- 输出:
- ['apple', 'banana', 'banana', 'banana', 'peach', 'peach', 'tomato', 'watermelon', 'lily', 'Lucy', 'Tom'] # 两个列表合并
extend多个列表合并元素
- names=['lucy','Lily','Jim','age']
- new_names="".join(names)
- print(new_names)
列表转换成字符串
4、元组(不可变列表)
元组一级元素不可被修改和删除。但是,元组中嵌套列表可以被修改
- tu3=(111,222,[(333,444)],555,(666,777),)
- tu3[2][0]=888
- print(tu3)
- #输出:(111, 222, [888], 555, (666, 777))
创建元组:
- tuple=('tom','lily',1,2,) 一般写元组时,建议在最后加一个逗号
- class tuple(object):
- """
- tuple() -> empty tuple
- tuple(iterable) -> tuple initialized from iterable's items
- If 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 0
- def 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 0
- def __add__(self, *args, **kwargs): # real signature unknown
- """ Return self+value. """
- pass
- def __contains__(self, *args, **kwargs): # real signature unknown
- """ Return key in self. """
- pass
- def __eq__(self, *args, **kwargs): # real signature unknown
- """ Return self==value. """
- pass
- def __getattribute__(self, *args, **kwargs): # real signature unknown
- """ Return getattr(self, name). """
- pass
- def __getitem__(self, *args, **kwargs): # real signature unknown
- """ Return self[key]. """
- pass
- def __getnewargs__(self, *args, **kwargs): # real signature unknown
- pass
- def __ge__(self, *args, **kwargs): # real signature unknown
- """ Return self>=value. """
- pass
- def __gt__(self, *args, **kwargs): # real signature unknown
- """ Return self>value. """
- pass
- def __hash__(self, *args, **kwargs): # real signature unknown
- """ Return hash(self). """
- pass
- def __init__(self, seq=()): # known special case of tuple.__init__
- """
- tuple() -> empty tuple
- tuple(iterable) -> tuple initialized from iterable's items
- If the argument is a tuple, the return value is the same object.
- # (copied from class doc)
- """
- pass
- def __iter__(self, *args, **kwargs): # real signature unknown
- """ Implement iter(self). """
- pass
- def __len__(self, *args, **kwargs): # real signature unknown
- """ Return len(self). """
- pass
- def __le__(self, *args, **kwargs): # real signature unknown
- """ Return self<=value. """
- pass
- def __lt__(self, *args, **kwargs): # real signature unknown
- """ Return self<value. """
- pass
- def __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. """
- pass
- def __ne__(self, *args, **kwargs): # real signature unknown
- """ Return self!=value. """
- pass
- def __repr__(self, *args, **kwargs): # real signature unknown
- """ Return repr(self). """
- pass
- def __rmul__(self, *args, **kwargs): # real signature unknown
- """ Return self*value. """
- pass
tuple方法
- str1="Mypython"
- tu1=tuple(str1)
- print(tu1)
- #输出:('M', 'y', 'p', 'y', 't', 'h', 'o', 'n')
字符串转换成元组
- names=['lucy','Lily','Jim','age']
- tu2=tuple(names)
- print(tu2)
- #输出:('lucy', 'Lily', 'Jim', 'age')
列表转换成元组
- name2=('lucy', 'Lily', 'Jim', 'age')
- list1=list(name2)
- print(list1)
- #输出:['lucy', 'Lily', 'Jim', 'age']
元组转换成列表
5、字典
字典一种key - value 的数据类型
字典的特性:
- dict是无序的
- key必须是唯一的,所以自动去重
语法:
- user_info={
- '':'Tom',
- '':'Jim',
- '':'Lucy',
- '':'Lily'
- }
- a = user_info.keys()
- print(a)
获取所有的key列表keys()
- #根据key获取值
- a = user_info.get("age")
- print(a)
- #如果没有值,返回None,不报错
- a = user_info.get("Age",19")
- print(a)
- #如果没有值,就返回19
根据key获取值get()
- user_info = {
- "name":"nick",
- "age":18,
- "job":"pythoner"
- }
- print(user_info.values())
- #返回 dict_values(['nick', 18, 'pythoner'])
获取所有的value列表values()
- user_info = {
- "name":"nick",
- "age":18,
- "job":"pythoner"
- }
- print(user_info.items())
- #输出:dict_items([('name', 'nick'), ('age', 18), ('job', 'pythoner')])
items()
- user_info = {
- "name":"nick",
- "age":18,
- "job":"pythoner"
- }
- #第一种删除方法
- print(user_info.pop('name'))
- #输出{'age': 18, 'job': 'pythoner'}
- #第二种随机删除字典里的key和value
- print(user_info.popitem())
删除pop()和随机删除popitem()
- user_info = {
- "name":"nick",
- "age":18,
- "job":"pythoner"
- }
- user_info2 = {
- "wage":800000000,
- "drem":"The knife girl",
- "name":"jack"
- }
- #有交叉的就覆盖了 没有交叉就创建
- user_info.update(user_info2)
- print(user_info)
- #输出:{'name': 'jack', 'age': 18, 'job': 'pythoner', 'wage': 800000000, 'drem': 'The knife girl'}
两个字典更新update()
- user_info = {
- "name":"nick",
- "age":18,
- "job":"pythoner"
- }
- #如果key不存在,则创建,如果存在,则返回已存在的值且不修改
- print(user_info.setdefault('slary',5000))
- print(user_info)
setdefault()
- user_info = {
- "name":"nick",
- "age":18,
- "job":"pythoner"
- }
- print(user_info.clear())
- print(user_info)
- #输出:{}
清空字典clear()
- user_info = {
- "name":"nick",
- "age":18,
- "job":"pythoner"
- }
- del user_info['name']
- print(user_info)
- #输出:{'age': 18, 'job': 'pythoner'}
del删除元素
- #根据序列,创建字典并指定统一的值
- info=dict.fromkeys(['slary','number'],5000)
- print(info)
- #输出:{'slary': 5000, 'number': 5000}
dict.fromkeys()
- province={
- '广东省':{'深圳市':['南山区','龙岗区','福田区'],
- '广州市':['荔湾区','海珠区','天河区'],
- '惠州市':['惠阳区','惠城区','惠东县']},
- '浙江省':{'杭州市':['西湖区','上城区','下城区'],
- '宁波市':['江北区','镇海区'],
- '嘉兴市':['南湖区','秀洲区']}
- }
- print(province['广东省'])
- {'深圳市': ['南山区', '龙岗区', '福田区'], '广州市': ['荔湾区', '海珠区', '天河区'], '惠州市': ['惠阳区', '惠城区', '惠东县']}
多级字典嵌套及操作
- province={
- '广东省':{'深圳市':['南山区','龙岗区','福田区'],
- '广州市':['荔湾区','海珠区','天河区'],
- '惠州市':['惠阳区','惠城区','惠东县']},
- '浙江省':{'杭州市':['西湖区','上城区','下城区'],
- '宁波市':['江北区','镇海区'],
- '嘉兴市':['南湖区','秀洲区']}
- }
- for k,v in province.items():
- print(k,v)
字典for循环
- user_info = {
- "name":"nick",
- "age":18,
- "job":"pythoner"
- }
- user_info2 = {
- "wage":800000000,
- "drem":"The knife girl",
- "name":"jack"
- }
- #有交叉的就覆盖了 没有交叉就创建
- user_info.update(user_info2)
- 或者
- user_info.update( "wage"=800000000, "drem"="The knife girl")
- print(user_info)
- #输出:{'name': 'jack', 'age': 18, 'job': 'pythoner', 'wage': 800000000, 'drem': 'The knife girl'}
update()补充
6、set()集合
集合是一个无序的,不重复的数据组合,它的主要作用如下:
- 去重,把一个列表变成集合,就自动去重了
- 关系测试,测试两组数据之前的交集、差集、并集等关系
- 集合中元素必须是不可变类型,不能包含列表、字典
- 集合只可以追加、删除,但是不可修改
- #列表
- list1=[1,4,5,7,3,6,7,9]
- # 创建集合 集合也是无序的
- set1=set(list1)
- print(set1,type(set1))
- set2=set([2,6,0,66,22,8,4])
- print(set1,set2)
- #输出:
- {1, 3, 4, 5, 6, 7, 9} <class 'set'>
- {1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}
创建集合
- list1=[1,4,5,7,3,6,7,9]
- set1=set(list1)
- set2=set([2,6,0,66,22,8,4])
- print(set1.intersection(set2))
- #输出:{4, 6}
交集intersection()
- list1=[1,4,5,7,3,6,7,9]
- set1=set(list1)
- set2=set([2,6,0,66,22,8,4])
- #求并集两个集合去重合并
- print(set1.union(set2))
- #输出:{0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}
并集union()
- list1=[1,4,5,7,3,6,7,9]
- set1=set(list1)
- set2=set([2,6,0,66,22,8,4])
- #set1中有 set2中没有的元素
- print(set1.difference(set2))
- #输出:{1, 3, 5, 7, 9}
- #set2中有 set1中没有的元素
- print(set2.difference(set1))
- #输出:{0, 2, 66, 8, 22}
差集difference()
- list1=[1,4,5,7,3,6,7,9]
- set1=set(list1)
- set2=set([2,6,0,66,22,8,4])
- #求子集
- #判断set1是否是set2的子集
- print(set1.issubset(set2))
- #判断set2是否是set1的子集
- print(set2.issubset(set1))
子集issubset()
- #求父集
- list1=[1,4,5,7,3,6,7,9]
- set1=set(list1)
- set2=set([2,6,0,66,22,8,4])
- # 判断set1是否是set2的父集
- print(set1.issuperset(set2))
- # 判断set2是否是set1的父集
- print(set2.issuperset(set1))
父集issuperset()
- list1=[1,4,5,7,3,6,7,9]
- set1=set(list1)
- set2=set([2,6,0,66,22,8,4])
- #对称差集
- print(set1.symmetric_difference(set2))
- #输出:
- {0, 1, 2, 66, 3, 5, 8, 7, 9, 22}
对称差集symmetric_difference()
- list1=[1,4,5,7,3,6,7,9]
- set1=set(list1)
- set2=set([2,6,0,66,22,8,4])
- #如果两个集合没有交集返回True 否则返回False
- print(set1.isdisjoint(set2))
- #输出:False
两个集合没有交集返回True
- print(set1 & set2) #交集
- print(set1 | set2) #并集
- print(set1 - set2) #差集
- print(set1 ^ set2) #对称差集
- list1=[1,4,5,7,3,6,7,9]
- set1=set(list1)
- set2=set([2,6,0,66,22,8,4])
- #集合中是没有插入的,只能添加
- set1.add(2) # 添加一项
- set3 = set([100, 200, 300])
- set1.update(set3) # 只能把一个集合更新到另一个集合中
- set1.remove(100) # 删除集合中一个元素
- set1.discard(100) # 删除一个元素 如果这个元素没有 不会报错 而remove会报错
集合其他基本操作
- # -*-coding:utf-8-*-
- # Author:sunhao
- product_list=[('Iphone',5800),
- ('Mac Pro',12000),
- ('Bike',800),
- ('Watch',10600),
- ('coffee',31)
- ]
- shopping_list=[]
- salary=input('请输入你的工资:')
- if salary.isdigit():
- salary=int(salary)
- while True:
- for index,item in enumerate(product_list):
- print(index,item)
- user_choice=input("请选择要买的商品:")
- if user_choice.isdigit():
- user_choice=int(user_choice)
- if user_choice<len(product_list) and user_choice >=0:
- p_item=product_list[user_choice]
- print(p_item)
- if p_item[1] <= salary:
- shopping_list.append(p_item)
- salary -= p_item[1]
- print('%s已添加至购物车 ,余额为%d'%(p_item[0],salary))
- else:
- print("\033[41;1m你的余额只剩%s\033[0m"%salary)
- else:
- print("商品不存在")
- elif user_choice=='q':
- print("-------shoppinglist------")
- for p in shopping_list:
- print(p[0])
- print('-------------------------')
- print('Your current balance:%s'%salary)
- exit()
- else:
- print('Invalid choice')
练习-购物车程序
三、文件处理
1、文件操作
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
- Somehow, it seems the love I knew was always the most destructive kind
- 不知为何,我经历的爱情总是最具毁灭性的的那种
- Yesterday when I was young
- 昨日当我年少轻狂
- The taste of life was sweet
- 生命的滋味是甜的
- As rain upon my tongue
- 就如舌尖上的雨露
- I teased at life as if it were a foolish game
- 我戏弄生命 视其为愚蠢的游戏
- The way the evening breeze
- 就如夜晚的微风
- May tease the candle flame
- 逗弄蜡烛的火苗
- The thousand dreams I dreamed
- 我曾千万次梦见
- The splendid things I planned
- 那些我计划的绚丽蓝图
- I always built to last on weak and shifting sand
- 但我总是将之建筑在易逝的流沙上
- I lived by night and shunned the naked light of day
- 我夜夜笙歌 逃避白昼赤裸的阳光
- And only now I see how the time ran away
- 事到如今我才看清岁月是如何匆匆流逝
- Yesterday when I was young
- 昨日当我年少轻狂
- So many lovely songs were waiting to be sung
- 有那么多甜美的曲儿等我歌唱
- So many wild pleasures lay in store for me
- 有那么多肆意的快乐等我享受
- And so much pain my eyes refused to see
- 还有那么多痛苦 我的双眼却视而不见
- I ran so fast that time and youth at last ran out
- 我飞快地奔走 最终时光与青春消逝殆尽
- I never stopped to think what life was all about
- 我从未停下脚步去思考生命的意义
- And every conversation that I can now recall
- 如今回想起的所有对话
- Concerned itself with me and nothing else at all
- 除了和我相关的 什么都记不得了
- The game of love I played with arrogance and pride
- 我用自负和傲慢玩着爱情的游戏
- And every flame I lit too quickly, quickly died
- 所有我点燃的火焰都熄灭得太快
- The friends I made all somehow seemed to slip away
- 所有我交的朋友似乎都不知不觉地离开了
- And only now I'm left alone to end the play, yeah
- 只剩我一个人在台上来结束这场闹剧
- Oh, yesterday when I was young
- 噢 昨日当我年少轻狂
- So many, many songs were waiting to be sung
- 有那么那么多甜美的曲儿等我歌唱
- So many wild pleasures lay in store for me
- 有那么多肆意的快乐等我享受
- And so much pain my eyes refused to see
- 还有那么多痛苦 我的双眼却视而不见
- There are so many songs in me that won't be sung
- 我有太多歌曲永远不会被唱起
- I feel the bitter taste of tears upon my tongue
- 我尝到了舌尖泪水的苦涩滋味
- The time has come for me to pay for yesterday
- 终于到了付出代价的时间 为了昨日
- When I was young
- 当我年少轻狂
文件示例lyrics
- f = open('lyrics','w','encoding=utf-8') #打开文件 f为文件句柄
- data = f.read() #读文件
- print(data)
- f.close() #关闭文件
- f.readable() #判断文件是否可读
- f.writable() #判断文件是都可写
- f.closed() #判断文件是否关闭 返回True 和 False
- 打开一个文件包含两部分资源:操作系统级打开的文件+应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
- 1、f.close() #回收操作系统级打开的文件
- 2、del f #回收应用程序级的变量
- 其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源,
- 而python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close()
- 我们推荐傻瓜式操作方式:使用with关键字来帮我们管理上下文
- with open('a.txt','w') as f:
- pass
- with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
- data=read_f.read()
- write_f.write(data)
注意f.close()
- f=open(...)是由操作系统打开文件,那么如果我们没有为open指定编码,那么打开文件的默认编码很明显是操作系统说了算了,操作系统会用自己的默认编码去打开文件,在windows下是gbk,在linux下是utf-8。
- 这就用到了上节课讲的字符编码的知识:若要保证不乱码,文件以什么方式存的,就要以什么方式打开。
- f=open('a.txt','r',encoding='utf-8')
打开文件注意字符编码
2、打开文件的模式
- #1. 打开文件的模式有(默认为文本模式):
- r,只读模式【默认模式,文件必须存在,不存在则抛出异常】
- w,只写模式【不可读;不存在则创建;存在则清空内容】
- a,只追加写模式【不可读;不存在则创建;存在则只追加内容】
- #2. 对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
- rb
- wb
- ab
- 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
- #3. 了解部分
- "+" 表示可以同时读写某个文件
- r+, 读写【可读,可写】
- w+,写读【可读,可写】
- a+, 写读【可读,可写】
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
rU
r+U
- x, 只写模式【不可读;不存在则创建,存在则报错】
- x+ ,写读【可读,可写】
- xb
3、操作文件的方法
- f.read() #读取所有内容,光标移动到文件末尾
- f.readline() #读取一行内容,光标移动到第二行首部
- f.readlines() #读取每一行内容,存放于列表中
- f.write('1111\n222\n') #针对文本模式的写,需要自己写换行符
- f.write('1111\n222\n'.encode('utf-8')) #针对b模式的写,需要自己写换行符
- f.writelines(['333\n','444\n']) #文件模式
- f.writelines([bytes('333\n',encoding='utf-8'),'444\n'.encode('utf-8')]) #b模式
- f = open('lyrics','r+',encoding='utf-8')
- for index,line in enumerate(f.readlines()):
- if index ==9:
- print(-------分隔符------) #第九行打印分隔符 跳出本次循环
- continue
- print(line)
示例
练习,利用b模式,编写一个cp工具,要求如下:
1. 既可以拷贝文本又可以拷贝视频,图片等文件
2. 用户一旦参数错误,打印命令的正确使用方法,如usage: cp source_file target_file
提示:可以用import sys,然后用sys.argv获取脚本后面跟的参数
- import sys
- if len(sys.argv) != 3:
- print('usage: cp source_file target_file')
- sys.exit()
- source_file,target_file=sys.argv[1],sys.argv[2]
- with open(source_file,'rb') as read_f,open(target_file,'wb') as write_f:
- for line in read_f:
- write_f.write(line)
练习
4、文件内光标移动
- f = open('lyrics','r+',encoding='utf-8')
- print(f.tell())
- f.read(16)
- print(f.tell())
- 输出:
- 0
- 16
tell()查看文件句柄指针的位置
- f = open('lyrics','r+',encoding='utf-8')
- print(f.tell())
- f.read(16)
- print(f.tell())
- f.seek(0) #移动到文件字符行首
- print(f.tell())
- 输出:
- 0
- 16
seek()移动文件句柄指针位置
- f = open('lyrics','r+',encoding='utf-8')
- print(f.encoding())
- 输出:
- utf-8
encoding()打印文件的编码
- f = open('lyrics','r+',encoding='utf-8')
- f.flush()
flush()强制刷新到硬盘
- # -*-coding:utf-8-*-
- import sys,time
- for i in range(10):
- sys.stdout.write('#')
- sys.stdout.flush() 如果不加flush 是等缓存满了之后一次性打印出来 加了之后是打印在一次强制刷新一次
- time.sleep(1)
flush()示例-打印进度条
- truncate是截断文件,所以文件的打开方式必须可写,但是不能用w或w+等方式打开,因为那样直接清空文件了,所以truncate要在r+或a或a+等模式下测试效果
truncate()截断文件
5、文件的修改
文件的数据是存放于硬盘上的,因而只存在覆盖、不存在修改这么一说,我们平时看到的修改文件,都是模拟出来的效果,具体的说有两种实现方式:
方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)
- import os
- with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
- data=read_f.read() #全部读入内存,如果文件很大,会很卡
- data=data.replace('alex','SB') #在内存中完成修改
- write_f.write(data) #一次性写入新文件
- os.remove('a.txt')
- os.rename('.a.txt.swap','a.txt')
方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件
- import os
- with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
- for line in read_f:
- line=line.replace('alex','SB')
- write_f.write(line)
- os.remove('a.txt')
- os.rename('.a.txt.swap','a.txt')
- # -*-coding:utf-8-*-
- # Author:sunhao
- f = open('yesterday','r',encoding='utf-8') #打开要修改的文件
- f_new = open('yesterday.bak','w',encoding='utf-8') #再打开一个要写入的新文件
- for line in f: #循环旧文件里的每一行
- if "肆意的快乐" in line: #每一行的type(line)是一个字符串
- line=line.replace("肆意的快乐",'肆意的痛苦') #字符串替换
- f_new.write(line) #写入新文件
- f.close() #关闭旧文件
- f_new.close() #关闭新文件
文件修改-示例
- #with语句
- 为了避免打开文件后忘记关闭,可以通过管理上下文,即:
- with open('file','r','encoding='uth-8'') as f: #f为文件句柄
- for line in f:
- print(line)
- 这样不用关闭文件
- 也可以同时操作多个文件
- with open('file1','r','encoding=utf-8') as f1,open('file2','r','encoding=utf-8') as f2:
- pass
with open()管理上下文
- import sys
- f = open('yesterday','r',encoding='utf-8')
- f_new = open('yesterday.bak','w',encoding='utf-8')
- find_str=sys.argv[1]
- replace_str=sys.argv[2]
- for line in f:
- if find_str in line:
- line=line.replace(find_str,replace_str)
- f_new.write(line)
- f.close()
- f_new.close()
练习-脚本传参实现sed替换
四、其他
1、字符编码与转码
1.在python2默认编码是ASCII, python3里默认是unicode
2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间
3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
- name='中国'
- new_name=name.encode('utf-8') #对字符串name编码 成二进制字节码
- print (new_name)
- 输出:
- b'\xe4\xb8\xad\xe5\x9b\xbd'
字符串编码成字节码
- name='中国'
- new_name=name.encode('utf-8') #对字符串name编码成二进制字节码
- renew_name=new_name.decode() #对二进制字节码进行解码
- print (renew_name)
- 输出:
- 中国
二进制字节码解码成字符串
上图仅适用于python2
- #-*- encoding:utf-8 -*-
- import sys
- print(sys.getdefaultencoding()) #打印系统默认编码
- s='你好'
- s_to_unicode=s.decode('utf-8') #先解码成unicode
- print(s_to_unicode,type(s_to_unicode))
- s_to_gbk=s_to_unicode.encode('gbk') #再编码成gbk
- print(s_to_gbk)
- print('你好')
- #把gbk再转成utf-8
- gbk_to_utf8=s_to_gbk.decode('gbk').encode('utf-8')
- print(gbk_to_utf8)
python2.X字符编码示列
- #在python3中默认的字符编码是unicode-utf8所以不需要decode了
- #-*-coding:gb2312 -*- #这个也可以去掉 #默认字符集为gb2312
- __author__ = 'Alex Li'
- import sys
- print(sys.getdefaultencoding())
- msg = "我爱北京天安门"
- #msg_gb2312 = msg.decode("utf-8").encode("gb2312") #在python2中需要先解码成unicode再编码成gb2312
- msg_gb2312 = msg.encode("gb2312") #python3中默认就是unicode utf8,不用再decode,喜大普奔
- gb2312_to_unicode = msg_gb2312.decode("gb2312")
- gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8")
- print(msg)
- print(msg_gb2312)
- print(gb2312_to_unicode)
- print(gb2312_to_utf8)
python3.x字符编码示例
- #十进制转二进制
- number=10
- to_bin=bin(number)
- print(to_bin)
- #输出:0b1010
- #十六进制转二进制
- number=0xff
- to_bin=bin(number)
- print(to_bin)
- #输出:0b11111111
bin()十进制(十六进制)转二进制
- #十六进制转十进制
- number=0xff
- to_int=int(number)
- print(to_int)
- #输出:255
- #二进制转十进制
- number=0b11111111
- to_int=int(number)
- print(to_int)
- #输出:255
int()十六进制(二进制)转十进制
- name = "python之路"
- a = bytes(name, encoding='utf-8')
- print(a)
- for i in a:
- print(i,bin(i))
- b = bytes(name, encoding='gbk')
- print(b)
- for i in b:
- print(i, bin(i))
示例
2、三元运算符
- result= 值1 if 条件 else 值2
- 如果条件为真:result=值1
- 如果条件为假:result=值2
- a,b,c=1,4,6
- d= a if a>b else c
三元运算符
3、input和raw_input
- # -*-coding:utf-8 -*-
- name=raw_input('请输入你的名字:') #raw_input仅适用于python2.7版本
- age=input('请输入你的年龄:')
- print("%s的年龄是%s:"%(name,age))
用户输入input()和raw_input()
- # 输入密码时,如果想要不可见,需要利用getpass 模块中的 getpass方法
- import getpass #导入getpass模块
- _username='sunhao'
- _password='abc123'
- username = input("usename:")
- password = getpass.getpass("password:")
- if _username==username and password == _password:
- print("Welcome user {name} login...".format(name=_username))
- else:
- print("Invalid username or password")
getpass
Python全栈开发之2、数据类型-数值、字符串、列表、字典、元组和文件处理的更多相关文章
- 战争热诚的python全栈开发之路
从学习python开始,一直是自己摸索,但是时间不等人啊,所以自己为了节省时间,决定报个班系统学习,下面整理的文章都是自己学习后,认为重要的需要弄懂的知识点,做出链接,一方面是为了自己找的话方便,一方 ...
- python全栈开发之路
一.Python基础 python简介 python数据类型(数字\字符串\列表) python数据类型(元组\字典) python数据类型(集合) python占位符%s,%d,%r,%f prin ...
- python全栈开发之OS模块的总结
OS模块 1. os.name() 获取当前的系统 2.os.getcwd #获取当前的工作目录 import os cwd=os.getcwd() # dir=os.listdi ...
- Python全栈开发之3、数据类型set补充、深浅拷贝与函数
转载请注明出处http://www.cnblogs.com/Wxtrkbc/p/5466082.html 一.基本数据类型补充 set是一个无序而且不重复的集合,有些类似于数学中的集合,也可以求交集, ...
- Python全栈开发之14、Javascript
一.简介 前面我们学习了html和css,但是我们写的网页不能动起来,如果我们需要网页出现各种效果,那么我们就要学习一门新的语言了,那就是JavaScript,JavaScript是世界上最流行的脚本 ...
- Python全栈开发之MySQL(二)------navicate和python操作MySQL
一:Navicate的安装 1.什么是navicate? Navicat是一套快速.可靠并价格相宜的数据库管理工具,专为简化数据库的管理及降低系统管理成本而设.它的设计符合数据库管理员.开发人员及中小 ...
- Python全栈开发之5、模块
一.模块 1.import导入模块 #1.定义 模块:用来从逻辑上组织python代码(变量,函数,类,逻辑),本质就是.py结尾的python文件,实现一个功能 包:python package 用 ...
- Python全栈开发之1、输入输出与流程控制
Python简介 python是吉多·范罗苏姆发明的一种面向对象的脚本语言,可能有些人不知道面向对象和脚本具体是什么意思,但是对于一个初学者来说,现在并不需要明白.大家都知道,当下全栈工程师的概念很火 ...
- Python全栈开发之21、django
http://www.cnblogs.com/wupeiqi/articles/5237704.html http://www.cnblogs.com/wupeiqi/articles/5246483 ...
随机推荐
- EntityManager的基本方法
1.Persistence 主要用来获取EntityManagerFactory的实例; 通过静态方法:createEntityManagerFactory 来实现: 该方法有两个重载版本: ...
- CSS的水平居中和垂直居中
水平居中如果不太熟悉盒子模型的话属实不太好理解,其实就是控制其他属性来让border之内的内容被控制在父容器中间就行了,最经典的就是使用{margin: 0 auto}了,控制其上下外边框为0,左右 ...
- Android源码开发利器——Java源码调试(基于4.1.2)
原文地址:http://blog.csdn.net/jinzhuojun/article/details/8868038 调试Android Java源码 草帽的后花园——Neo 写在之前的 ...
- 「Luogu P5601」小D与笔试
题目链接 戳我 \(Solution\) 这道题官方题解的做法太复杂了,还需要扫字符串. 其实只需要两个\(map\)就好了. 一个\(map<string,stirng>\)用来记录题目 ...
- DB 分库分表(1):拆分实施策略和示例演示
DB 分库分表(1):拆分实施策略和示例演示 第一部分:实施策略 1.准备阶段 对数据库进行分库分表(Sharding化)前,需要开发人员充分了解系统业务逻辑和数据库schema.一个好的建议是绘制一 ...
- SpringMVC接收请求参数和页面传参
接收请求参数: 1,使用HttpServletRequest获取 @RequestMapping("/login.do") public String login(HttpServ ...
- Java 注解方式校验请求参数
1. 参数校验常用注解 注解 验证的数据类型 备注 Null 任意类型 参数值必须是 Null NotNull ...
- 邻居子系统 之 邻居项查找neigh_lookup、___neigh_lookup_noref
概述 邻居项查找是通过neigh_lookup相关函数来进行的: ___neigh_lookup_noref,该函数根据输出设备和主键值(IPv4为下一跳ip地址)在邻居项hash表中查找,找到则返回 ...
- redis如何清空当前缓存和所有缓存
Windows环境下使用命令行进行redis缓存清理1.redis安装目录下输入cmd2.redis-cli -p 端口号3.flushdb 清除当前数据库缓存4.flushall 清除 ...
- JDBC——JDBC基础
1.JDBC与数据库的交互过程概括性来说,JDBC与数据库交互有以下这些步骤:1.建立一个到数据库的连接.2.在数据库中对表执行检索.创建,或修改的SQL查询.3.关闭到数据库的连接.JDBC的类和接 ...