一、输入(raw_input)=====》python2.x版本
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 # 将用户输入的内容赋值给 name 变量 5 name = raw_input("请输入用户名:") 6 7 # 打印输入的内容 8 print name
输入密码时,如果想要不可见,需要利用getpass 模块中的 getpass方法,即:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import getpass 5 6 # 将用户输入的内容赋值给 name 变量 7 pwd = getpass.getpass("请输入密码:") 8 9 # 打印输入的内容 10 print pwd
二、 流程控制和缩进(if语句 while循环)
Python语言中严格区分缩进的大小,缩进不正确会报错。
1 #!/usr/bin/env python 2 # -*- coding: encoding -*- 3 4 # 提示输入用户名和密码 5 6 # 验证用户名和密码 7 # 如果错误,则输出用户名或密码错误 8 # 如果成功,则输出 欢迎,XXX! 9 10 11 import getpass 12 13 14 name = raw_input('请输入用户名:') 15 pwd = getpass.getpass('请输入密码:') 16 17 if name == "zhao" and pwd == "cmd": 18 print "欢迎,zhao!" 19 else: 20 print "用户名和密码错误"
1.单个if判断语句
if 条件: 代码块 else: 代码块
2.多个if判断语句
1 if 条件: 2 3 代码块 4 5 elif 条件: 6 7 代码块 8 9 elif 条件: 10 11 代码块 12 13 else: 14 15 代码块
while循环
1、基本循环
1 while 条件: 2 3 # 循环体 4 5 # 如果条件为真,那么循环体则执行 6 # 如果条件为假,那么循环体不执行
2、break
break用于退出所有循环
1 while True: 2 print "123" 3 break 4 print "456"
3、continue
continue用于退出当前循环,继续下一次循环
1 while True: 2 print "123" 3 continue 4 print "456"
#例如,当为真,则打印yes,是个无限循环语句 while True: print('yes') #也可以通过break,或continue关键字去控制语句的输出,如下 count = 0 while True: if count >2: break #当条件满足时,则使用break中断语句的执行 count +=1 #每一次循环,都在count基础上加1
for循环
#for循环与while循环,for循环是可以预知循环次数的,不需要人为大中断,也能自己结束,而while是需要一个结束条件的。例如 #语法 for iterating_var in sequence: statements(s) #实例 for number in range(10): print(number) #将会打印输出0-9
and ... or ... not
#and or not 一般用于多重条件判断时使用,例如 a = 1 b = 2 if a > 0 and b > a: print(a+b) #打印结果将输出3,只要其中一个条件不满,则不会执行语句块的代码 if a < 0 or b>a: print(a+b) #打印结果将输出3,只要有其中任一个条件满足,则执行语句代码块 if not a: print(a+b) #这里不会输出任何东西,因为a是大于0,为真,只有条件为假,才会执行代码快语句
三、python运算符
1、python赋值运算
运算符 | 描述 | 示例 |
---|---|---|
= | 简单的赋值运算符,赋值从右侧操作数左侧操作数 | c = a + b将指定的值 a + b 到 c |
+= | 加法AND赋值操作符,它增加了右操作数左操作数和结果赋给左操作数 | c += a 相当于 c = c + a |
-= | 减AND赋值操作符,它减去右边的操作数从左边操作数,并将结果赋给左操作数 | c -= a 相当于 c = c - a |
*= | 乘法AND赋值操作符,它乘以右边的操作数与左操作数,并将结果赋给左操作数 | c *= a 相当于 c = c * a |
/= | 除法AND赋值操作符,它把左操作数与正确的操作数,并将结果赋给左操作数 | c /= a 相当于= c / a |
%= | 模量AND赋值操作符,它需要使用两个操作数的模量和分配结果左操作数 | c %= a is equivalent to c = c % a |
**= | 指数AND赋值运算符,执行指数(功率)计算操作符和赋值给左操作数 | c **= a 相当于 c = c ** a |
//= | 地板除,并分配一个值,执行地板除对操作和赋值给左操作数 | c //= a 相当于 c = c // a |
1.2、Python位运算符:
操作符 | 描述 | 示例 |
---|---|---|
& | 二进制和复制操作了一下,结果,如果它存在于两个操作数。 | (a & b) = 12 即 0000 1100 |
| | 二进制或复制操作了一个比特,如果它存在一个操作数中。 | (a | b) = 61 即 0011 1101 |
^ | 二进制异或运算符的副本,如果它被设置在一个操作数而不是两个比特。 | (a ^ b) = 49 即 0011 0001 |
~ | 二进制的补运算符是一元的,并有“翻转”位的效果。 | (~a ) = -61 即 1100 0011以2的补码形式由于带符号二进制数。 |
<< | 二进位向左移位运算符。左操作数的值左移由右操作数指定的位数。 | a << 2 = 240 即 1111 0000 |
>> | 二进位向右移位运算符。左操作数的值是由右操作数指定的位数向右移动。 | a >> 2 = 15 即 0000 1111 |
2、比较运算:
3、赋值运算
四、赋值运算
五、Python逻辑运算符
运算符 | 描述 | 示例 |
---|---|---|
and | 所谓逻辑与运算符。如果两个操作数都是真的,那么则条件成立。 | (a and b) 为 true. |
or | 所谓逻辑OR运算符。如果有两个操作数都是非零然后再条件变为真。 | (a or b) 为 true. |
not | 所谓逻辑非运算符。用于反转操作数的逻辑状态。如果一个条件为真,则逻辑非运算符将返回false。 |
not(a and b) 为 false. |
五、python基本数据类型
查看类的所有方法:dir(类名)如下,就打印出了所有的类方法。
如下:
# python3.x dir(int) # ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] # python 2.x dir(int) # ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
1、数字
int(整型)
在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
在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__("1") 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') '1011111' #在内存中占多少个字节 >>> a = 95 >>> a.__sizeof__() 28
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'x00x10', byteorder='big') >>> int.from_bytes(b'x00x10', byteorder='little') >>> int.from_bytes(b'xfcx00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'xfcx00', 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'x04x00' >>> (1024).to_bytes(10, byteorder='big') b'x00x00x00x00x00x00x00x00x04x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'xffxffxffxffxffxffxffxffxfcx00' >>> x = 1000 >>> x.to_bytes((x.bit_length() // 8) + 1, byteorder='little') b'xe8x03' """ 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"""
2、布尔值
真或假
1 或 0
3、字符串
"Hello World!"
s = "nick" #索引 print(s[0]) print(s[1]) print(s[2]) print(s[3]) #长度 ret = len(s) print(ret) #切片 print(s[1:3]) print(s.rsplit("ic")) #替换 name = "Nick is good, Today is nice day." a = name.replace("good","man") print(a) #连接两个字符串 li = ["nick","serven"] a = "".join(li) b = "_".join(li) print(a) print(b) #指定的分隔符将字符串进行分割 a = s.rpartition("i") print(a) #分割,前,中,后三部分 name = "Nick is good, Today is nice day." a = name.partition("good") print(a) #for循环 for i in s: print(i) for i in range(5): print(i) # 反转 s = 'ssssssssss111' print(s[::-1]) # 111ssssssssss
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__ """ 首字母变大写 name = "nick is good, Today is nice day." a = name.capitalize() print(a) """ 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__ """ 首字母变小写 name = "Nick is good, Today is nice day. a =name.casefold() print(a) """ 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__ """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无。 name = "Nick is good, Today is nice day. a = name.center(60,'$') print(a) """ 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__ """ 子序列个数,0到26中n出现了几次。 name = "nck is good, Today is nice day. a = name.count("n",0,26) print(a) """ 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__ """ """ 编码,针对unicode. temp = "烧饼 temp.encode("unicode") """ 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__ """ """ 是否以XX结束,0到4是否以k结尾 name = "nck is good, Today is nice day. a = name.endswith("k",0,4) print(a) """ 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__ """ """ 将tab转换成空格,默认一个tab转换成8个空格 a = n.expandtabs() b = n.expandtabs(16) print(a) print(b) """ 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__ """ """ 寻找子序列位置,如果没找到,返回 -1。 name = "nck is good, Today is nice day. " a = name.find("nickk") print(a) """ 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 """ """ 字符串格式化,动态参数 name = "nck is good, Today is nice day. " a = name.format() print(a) """ 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__ """ """ dict = {'Foo': 54.23345} fmt = "Foo = {Foo:.3f}" result = fmt.format_map(dict) print(result) #Foo = 54.233 """ 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__ """ """ #子序列位置,如果没有找到就报错 name = "nck is good, Today is nice day. " a = name.index("nick") print(a) """ S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0 def isalnum(self): # real signature unknown; restored from __doc__ """ """ 是否是字母和数字 name = "nck is good, Today is nice day. " a = name.isalnum() print(a) """ 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__ """ """ 是否是字母 name = "nck is good, Today is nice day. " a = name.isalpha() print(a) """ 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__ """ 检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。 """ 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__ """ """ 是否是数字 name = "nck is good, Today is nice day. " a = name.isdigit() print(a) """ 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__ """ """ 是否小写 name = "nck is good, Today is nice day. " a = name.islower() print(a) """ 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__ """ """ 检查是否只有数字字符组成的字符串 name = "111111111111111” a = name.isnumeric() print(a) """ 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__ """ """ 判断字符串中所有字符是否都属于可见字符 name = "nck is good, Today is nice day. " a = name.isprintable() print(a) """ 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__ """ """ 字符串是否只由空格组成 name = " " a = name.isspace() print(a) """ 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__ """ """ 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写 name = "Nick, Today." a = name.istitle() print(a) """ """ 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__ """ """ 检测字符串中所有的字母是否都为大写 name = "NICK" a = name.isupper() print(a) """ 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__ """ """ 连接两个字符串 li = ["nick","serven"] a = "".join(li) b = "_".join(li) print(a) print(b) """ 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__ """ """ 向左对齐,右侧填充 name = "nck is good, Today is nice day. " a = name.ljust(66) print(a) """ 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__ """ """ 容左对齐,右侧填充 name = "NiNi" a = name.lower() print(a) """ 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 """ """ 用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。 from string import maketrans intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!"; print str.translate(trantab); """ 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__ """ """ 分割,前,中,后三部分 name = "Nick is good, Today is nice day." a = name.partition("good") print(a) """ 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__ """ """ 替换 name = "Nick is good, Today is nice day." a = name.replace("good","man") print(a) """ 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__ """ """ 返回字符串最后一次出现的位置,如果没有匹配项则返回-1 """ S.rfind(sub[, start[, end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ """ 返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常 """ S.rindex(sub[, start[, end]]) -> int Like S.rfind() but raise ValueError when the substring is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ """ 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串 str = "this is string example....wow!!!" print(str.rjust(50, '$')) """ 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__ """ """ 指定分隔符对字符串进行切片 name = "Nick is good, Today is nice day." a = name.rsplit("is") print(a) """ 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__ """ """ 删除 string 字符串末尾的指定字符(默认为空格) """ 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__ """ """ 通过指定分隔符对字符串进行切片 str = "Line1-abcdef Line2-abc Line4-abcd"; print str.split( ); print str.split(' ', 1 ); """ 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__ """ """ 检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False """ 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__ """ """ 返回指定长度的字符串,原字符串右对齐,前面填充0 """ 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 "" 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 __format__(self, format_spec): # real signature unknown; restored from __doc__ """ S.__format__(format_spec) -> str Return a formatted version of S as described by format_spec. """ return "" 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, value='', encoding=None, errors='strict'): # known special case of str.__init__ """ 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'. # (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 __mod__(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 __rmod__(self, *args, **kwargs): # real signature unknown """ Return value%self. """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __str__(self, *args, **kwargs): # real signature unknown """ Return str(self). """ pass
4、列表
list = ['Google', 'baidu', 'taobao']
#在列表末尾添加新的对象 list = ['Google', 'baidu', 'T'] list.append('taobao') print(list) #将指定对象插入列表 list = ['Google', 'baidu', 'T','baidu'] list.insert(1,"Nick") print(list) #在列表末尾追加另一个序列中的多个值 list = ['Google', 'baidu', 'T','baidu'] list2 = ['nick','baidu'] list.extend(list2) print(list) #统计某个元素在列表中出现的次数 list = ['Google', 'baidu', 'T','baidu'] a = list.count('baidu') print(a) #从列表中找出某个值第一个匹配项的索引位置 list = ['Google', 'baidu', 'T','baidu'] a = list.index('baidu') print(a) #移除列表中的一个元素(默认最后一个元素) list = ['Google', 'baidu', 'T','baidu'] list.pop() print(list) #移除列表中某个值的第一个匹配项 list = ['Google', 'baidu', 'T','baidu'] list.remove('baidu') print(list) #清空列表 list = ['Google', 'baidu', 'T'] list.clear() print(list) #删除指定索引位置 list = ['Google', 'baidu', 'T','baidu'] del list[2] print(list) list = ['Google', 'baidu', 'T','baidu'] del list[1:3] -->顾头不顾尾 print(list) #复制列表 list = ['Google', 'baidu', 'T'] list2 = list.copy() print(list2) #对原列表进行排序 list = ['Google', 'baidu', 'T','baidu'] list.sort() print(list) #反向列表中元素 list = ['Google', 'baidu', 'T','baidu'] list.reverse() print(list)
class list(object): """ list() -> new empty list list(iterable) -> new list initialized from iterable's items """ def append(self, p_object): # real signature unknown; restored from __doc__ """ 用于在列表末尾添加新的对象 list = ['Google', 'baidu', 'T'] list.append('taobao') print(list) """ """ L.append(object) -> None -- append object to end """ pass def clear(self): # real signature unknown; restored from __doc__ """ 用于清空列表 list = ['Google', 'baidu', 'T'] list.clear() print(list) """ """ L.clear() -> None -- remove all items from L """ pass def copy(self): # real signature unknown; restored from __doc__ """ 用于复制列表 list = ['Google', 'baidu', 'T'] list2 = list.copy() print(list2) """ """ L.copy() -> list -- a shallow copy of L """ return [] def count(self, value): # real signature unknown; restored from __doc__ """ 统计某个元素在列表中出现的次数 list = ['Google', 'baidu', 'T','baidu'] a = list.count('baidu') print(a) """ """ L.count(value) -> integer -- return number of occurrences of value """ return 0 def extend(self, iterable): # real signature unknown; restored from __doc__ """ 在列表末尾一次性追加另一个序列中的多个值 list = ['Google', 'baidu', 'T','baidu'] list2 = ['nick','baidu'] list.extend(list2) print(list) """ """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """ pass def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ """ 用于从列表中找出某个值第一个匹配项的索引位置 list = ['Google', 'baidu', 'T','baidu'] a = list.index('baidu') print(a) """ L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__ """ 用于将指定对象插入列表 list = ['Google', 'baidu', 'T','baidu'] list.insert(1,"Nick") print(list) """ """ L.insert(index, object) -- insert object before index """ pass def pop(self, index=None): # real signature unknown; restored from __doc__ """ 移除列表中的一个元素(默认最后一个元素)。 list = ['Google', 'baidu', 'T','baidu'] list.pop() print(list) """ """ L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range. """ pass def remove(self, value): # real signature unknown; restored from __doc__ """ 移除列表中某个值的第一个匹配项 list = ['Google', 'baidu', 'T','baidu'] list.remove('baidu') print(list) """ """ L.remove(value) -> None -- remove first occurrence of value. Raises ValueError if the value is not present. """ pass def reverse(self): # real signature unknown; restored from __doc__ """ 用于反向列表中元素 list = ['Google', 'baidu', 'T','baidu'] list.reverse() print(list) """ """ L.reverse() -- reverse *IN PLACE* """ pass def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__ """ 用于对原列表进行排序 list = ['Google', 'baidu', 'T','baidu'] list.sort() print(list) """ """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """ pass 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 __delitem__(self, *args, **kwargs): # real signature unknown """ Delete self[key]. """ 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, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ 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 __iadd__(self, *args, **kwargs): # real signature unknown """ Implement self+=value. """ pass def __imul__(self, *args, **kwargs): # real signature unknown """ Implement self*=value. """ pass def __init__(self, seq=()): # known special case of list.__init__ """ list() -> new empty list list(iterable) -> new list initialized from iterable's items # (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 __reversed__(self): # real signature unknown; restored from __doc__ """ L.__reversed__() -- return a reverse iterator over the list """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __setitem__(self, *args, **kwargs): # real signature unknown """ Set self[key] to value. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ L.__sizeof__() -- size of L in memory, in bytes """ pass __hash__ = None
5、元组(不可修改)
name = ('zhao','jenney')
#索引 name = ('nick','jenney') a = name[0] print(a) #获取指定元素的索引位置 name = ('nick','jenney') a = name.index('nick') print(a) #切片 name = ('nick','jenney') a = name[0:1] print(a) #计算元素出现的个数 name = ('nick','jenney') a = name.count('nick') print(a) #长度 name = ('nick','jenney') a = len(name) print(a) #for循环 name = ('nick','jenney') for i in name: print(i)
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__ """ 计算元素出现的个数 name = ('nick','jenney') a = name.count('nick') print(a) """ """ 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__ """ 获取指定元素的索引位置 name = ('nick','jenney') a = name.index('nick') print(a) """ """ 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
6、字典(无序)
user_info = {
"name":"zhao",
"age":18,
"job":"pythoner"
}
1 user_info = { 2 "name":"nick", 3 "age":18, 4 "job":"pythoner" 5 } 6 7 #根据key获取值 8 a = user_info.get("age") 9 print(a) 10 a = user_info.get("Age",19") 11 print(a) 12 13 #所有的key 列表 14 a = user_info.keys() 15 print(a) 16 17 #所有的值,values 18 a = user_info.values() 19 print(a) 20 21 #所有项的列表形式 22 a = user_info.items() 23 print(a) 24 25 26 #获取并在字典中移除 27 user_info.pop('age') 28 print(user_info) 29 30 #随机并在字典中移除 31 user_info.popitem() 32 user_info.popitem() 33 print(user_info) 34 35 #清除内容 36 a = user_info.clear() 37 print(a) 38 39 40 #浅拷贝 41 a = user_info.copy() 42 print(a) 43 44 #如果key不存在,则创建,如果存在,则返回已存在的值且不修改 45 a = user_info.setdefault("age") 46 print(a) 47 user_info.setdefault("cool") 48 print(user_info) 49 50 #从序列键和值设置为value来创建一个新的字典 51 a = dict.fromkeys(user_info) 52 print(("new dict: %s") % str(a)) 53 54 55 #更新(两个字典) 56 user_info = { 57 "name":"nick", 58 "age":18, 59 "job":"pythoner" 60 } 61 user_info2 = { 62 "wage":800000000, 63 "drem":"The knife girl" 64 } 65 user_info.update(user_info2) 66 print(user_info)
1 class dict(object): 2 """ 3 dict() -> new empty dictionary 4 dict(mapping) -> new dictionary initialized from a mapping object's 5 (key, value) pairs 6 dict(iterable) -> new dictionary initialized as if via: 7 d = {} 8 for k, v in iterable: 9 d[k] = v 10 dict(**kwargs) -> new dictionary initialized with the name=value pairs 11 in the keyword argument list. For example: dict(one=1, two=2) 12 """ 13 def clear(self): # real signature unknown; restored from __doc__ 14 """ 15 清除内容 16 user_info = { 17 "name":"nick", 18 "age":18, 19 "job":"pythoner" 20 a = user_info.clear() 21 print(a) 22 """ 23 """ D.clear() -> None. Remove all items from D. """ 24 pass 25 26 def copy(self): # real signature unknown; restored from __doc__ 27 """ 28 浅拷贝 29 user_info = { 30 "name":"nick", 31 "age":18, 32 "job":"pythoner" 33 } 34 a = user_info.copy() 35 print(a) 36 """ 37 """ D.copy() -> a shallow copy of D """ 38 pass 39 40 @staticmethod # known case 41 def fromkeys(*args, **kwargs): # real signature unknown 42 """ 43 从序列键和值设置为value来创建一个新的字典 44 user_info = { 45 "name":"nick", 46 "age":18, 47 "job":"pythoner" 48 } 49 a = dict.fromkeys(user_info) 50 print(("new dict: %s") % str(a)) 51 """ 52 """ Returns a new dict with keys from iterable and values equal to value. """ 53 pass 54 55 def get(self, k, d=None): # real signature unknown; restored from __doc__ 56 """ 57 根据key获取值,d是默认值 58 user_info = { 59 "name":"nick", 60 "age":18, 61 "job":"pythoner" 62 } 63 a = user_info.get("age") 64 print(a) 65 """ 66 """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ 67 pass 68 69 def items(self): # real signature unknown; restored from __doc__ 70 """ 71 所有项的列表形式 72 user_info = { 73 "name":"nick", 74 "age":18, 75 "job":"pythoner" 76 } 77 a = user_info.items() 78 print(a) 79 """ 80 """ D.items() -> a set-like object providing a view on D's items """ 81 pass 82 83 def keys(self): # real signature unknown; restored from __doc__ 84 """ 85 所有的key 列表 86 user_info = { 87 "name":"nick", 88 "age":18, 89 "job":"pythoner" 90 } 91 a = user_info.keys() 92 print(a) 93 """ 94 """ D.keys() -> a set-like object providing a view on D's keys """ 95 pass 96 97 def pop(self, k, d=None): # real signature unknown; restored from __doc__ 98 """ 99 获取并在字典中移除 100 user_info = { 101 "name":"nick", 102 "age":18, 103 "job":"pythoner" 104 } 105 user_info.pop('age') 106 print(user_info) 107 """ 108 """ 109 D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 110 If key is not found, d is returned if given, otherwise KeyError is raised 111 """ 112 pass 113 114 def popitem(self): # real signature unknown; restored from __doc__ 115 """ 116 随机并在字典中移除 117 user_info = { 118 "name":"nick", 119 "age":18, 120 "job":"pythoner" 121 } 122 user_info.popitem() 123 user_info.popitem() 124 print(user_info) 125 """ 126 """ 127 D.popitem() -> (k, v), remove and return some (key, value) pair as a 128 2-tuple; but raise KeyError if D is empty. 129 """ 130 pass 131 132 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ 133 """ 134 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 135 user_info = { 136 "name":"nick", 137 "age":18, 138 "job":"pythoner" 139 } 140 a = user_info.setdefault("age") 141 print(a) 142 user_info.setdefault("cool") 143 print(user_info) 144 """ 145 """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ 146 pass 147 148 def update(self, E=None, **F): # known special case of dict.update 149 """ 150 更新(两个字典) 151 user_info = { 152 "name":"nick", 153 "age":18, 154 "job":"pythoner" 155 } 156 user_info2 = { 157 "wage":800000000, 158 "drem":"The knife girl" 159 } 160 user_info.update(user_info2) 161 print(user_info) 162 """ 163 """ 164 D.update([E, ]**F) -> None. Update D from dict/iterable E and F. 165 If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] 166 If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v 167 In either case, this is followed by: for k in F: D[k] = F[k] 168 """ 169 pass 170 171 def values(self): # real signature unknown; restored from __doc__ 172 """ 173 所有的值,values 174 user_info = { 175 "name":"nick", 176 "age":18, 177 "job":"pythoner" 178 } 179 a = user_info.values() 180 print(a) 181 """ 182 """ D.values() -> an object providing a view on D's values """ 183 pass 184 185 def __contains__(self, *args, **kwargs): # real signature unknown 186 """ True if D has a key k, else False. """ 187 pass 188 189 def __delitem__(self, *args, **kwargs): # real signature unknown 190 """ Delete self[key]. """ 191 pass 192 193 def __eq__(self, *args, **kwargs): # real signature unknown 194 """ Return self==value. """ 195 pass 196 197 def __getattribute__(self, *args, **kwargs): # real signature unknown 198 """ Return getattr(self, name). """ 199 pass 200 201 def __getitem__(self, y): # real signature unknown; restored from __doc__ 202 """ x.__getitem__(y) <==> x[y] """ 203 pass 204 205 def __ge__(self, *args, **kwargs): # real signature unknown 206 """ Return self>=value. """ 207 pass 208 209 def __gt__(self, *args, **kwargs): # real signature unknown 210 """ Return self>value. """ 211 pass 212 213 def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ 214 """ 215 dict() -> new empty dictionary 216 dict(mapping) -> new dictionary initialized from a mapping object's 217 (key, value) pairs 218 dict(iterable) -> new dictionary initialized as if via: 219 d = {} 220 for k, v in iterable: 221 d[k] = v 222 dict(**kwargs) -> new dictionary initialized with the name=value pairs 223 in the keyword argument list. For example: dict(one=1, two=2) 224 # (copied from class doc) 225 """ 226 pass 227 228 def __iter__(self, *args, **kwargs): # real signature unknown 229 """ Implement iter(self). """ 230 pass 231 232 def __len__(self, *args, **kwargs): # real signature unknown 233 """ Return len(self). """ 234 pass 235 236 def __le__(self, *args, **kwargs): # real signature unknown 237 """ Return self<=value. """ 238 pass 239 240 def __lt__(self, *args, **kwargs): # real signature unknown 241 """ Return self<value. """ 242 pass 243 244 @staticmethod # known case of __new__ 245 def __new__(*args, **kwargs): # real signature unknown 246 """ Create and return a new object. See help(type) for accurate signature. """ 247 pass 248 249 def __ne__(self, *args, **kwargs): # real signature unknown 250 """ Return self!=value. """ 251 pass 252 253 def __repr__(self, *args, **kwargs): # real signature unknown 254 """ Return repr(self). """ 255 pass 256 257 def __setitem__(self, *args, **kwargs): # real signature unknown 258 """ Set self[key] to value. """ 259 pass 260 261 def __sizeof__(self): # real signature unknown; restored from __doc__ 262 """ D.__sizeof__() -> size of D in memory, in bytes """ 263 pass 264 265 __hash__ = None
7、set集合(无序、不重复)
s = set()
a = {'nick','jenny','zhao'}
1 #添加元素 2 a = {'nick','jenny','zhao'} 3 a.add('The knife girl') 4 print(a) 5 6 #更新 7 a = {'nick','jenny','zhao'} 8 b = {'nick','jenny','The knife girl'} 9 a.update(b) 10 print(a) 11 12 13 #a中存在。b中不存在,赋给新值 14 a = {'nick','jenny','zhao'} 15 b = {'nick','jenny','The knife girl'} 16 set = a.difference(b) 17 print(set) 18 19 #a中存在。b中不存在,并更新a 20 a = {'nick','jenny','zhao'} 21 b = {'nick','jenny','The knife girl'} 22 a.difference_update(b) 23 print(a) 24 25 #交集,赋给新值 26 a = {'nick','jenny','zhao'} 27 b = {'nick','jenny','The knife girl'} 28 set = a.intersection(b) 29 print(set) 30 31 #交集,更新a 32 a = {'nick','jenny','zhao'} 33 b = {'nick','jenny','The knife girl'} 34 a.intersection_update(b) 35 print(a) 36 37 #对称交集 38 a = {'nick','jenny','zhao'} 39 b = {'nick','jenny','The knife girl'} 40 set = a.symmetric_difference(b) 41 print(set) 42 43 #对称交集,更新a 44 a = {'nick','jenny','zhao'} 45 b = {'nick','jenny','The knife girl'} 46 a.symmetric_difference_update(b) 47 print(a) 48 49 #并集,赋给新值 50 a = {'nick','jenny','zhao'} 51 b = {'nick','jenny','The knife girl'} 52 set = a.union(b) 53 print(set) 54 55 #如果没有交集,返回True,否则返回False 56 a = {'nick','jenny','zhao'} 57 b = {'nick','jenny','The knife girl'} 58 set = a.isdisjoint(b) 59 print(set) 60 61 #是否是子序列 62 a = {'nick','jenny','zhao'} 63 b = {'nick','jenny'} 64 set = a.issubset(b) 65 print(set) 66 67 #是否是父序列 68 a = {'nick','jenny','zhao'} 69 b = {'nick','jenny'} 70 set = a.issuperset(b) 71 print(set) 72 73 74 #移除指定元素,不存在不报错 75 a = {'nick','jenny','zhao'} 76 a.discard('suo') 77 print(a) 78 79 #移除指定元素,不存在则报错 80 a = {'nick','jenny','zhao'} 81 a.remove('suo') 82 print(a) 83 a.remove('suo') 84 print(a) 85 86 #移除随机元素,并赋给新值 87 a = {'nick','jenny','zhao'} 88 set = a.pop() 89 print(set) 90 91 #清空 92 a = {'nick','jenny','zhao'} 93 a.clear() 94 print(a)
1 class set(object): 2 """ 3 set() -> new empty set object 4 set(iterable) -> new set object 5 6 Build an unordered collection of unique elements. 7 """ 8 def add(self, *args, **kwargs): # real signature unknown 9 """添加元素 10 >>> a = {'nick','jenny','suo'} 11 >>> a.add('nick') 12 >>> a 13 {'suo', 'jenny', 'nick'} 14 >>> a.add('love') 15 >>> a 16 {'suo', 'love', 'jenny', 'nick'} 17 """ 18 """ 19 Add an element to a set. 20 21 This has no effect if the element is already present. 22 """ 23 pass 24 25 def clear(self, *args, **kwargs): # real signature unknown 26 """清除内容 27 >>> a = {'nick','jenny','suo'} 28 >>> a.clear() 29 >>> a 30 set() 31 """ 32 """ Remove all elements from this set. """ 33 pass 34 35 def copy(self, *args, **kwargs): # real signature unknown 36 """浅拷贝 37 >>> a = {'nick','jenny','suo'} 38 >>> b = a.copy() 39 >>> b 40 {'suo', 'jenny', 'nick'} 41 """ 42 """ Return a shallow copy of a set. """ 43 pass 44 45 def difference(self, *args, **kwargs): # real signature unknown 46 """A中存在,B中不存在 47 >>> a = {'nick','jenny','suo'} 48 >>> b = {'nick','jenny','The knife girl'} 49 >>> a.difference(b) 50 {'suo'} 51 """ 52 """ 53 Return the difference of two or more sets as a new set. 54 55 (i.e. all elements that are in this set but not the others.) 56 """ 57 pass 58 59 def difference_update(self, *args, **kwargs): # real signature unknown 60 """从当前集合中删除和B中相同的元素 61 >>> a = {'nick','jenny','suo'} 62 >>> b = {'nick','jenny','The knife girl'} 63 >>> a.difference_update(b) 64 >>> a 65 {'suo'} 66 """ 67 """ Remove all elements of another set from this set. """ 68 pass 69 70 def discard(self, *args, **kwargs): # real signature unknown 71 """移除指定元素,不存在不报错 72 >>> a = {'nick','jenny','suo'} 73 >>> a.discard('suo') 74 >>> a 75 {'jenny', 'nick'} 76 >>> a.discard('The knife girl') 77 >>> a 78 {'jenny', 'nick'} 79 """ 80 """ 81 Remove an element from a set if it is a member. 82 83 If the element is not a member, do nothing. 84 """ 85 pass 86 87 def intersection(self, *args, **kwargs): # real signature unknown 88 """a与b的交集 89 >>> a = {'nick','jenny','suo'} 90 >>> b = {'nick','jenny','The knife girl'} 91 >>> a.intersection(b) 92 {'jenny', 'nick'} 93 """ 94 """ 95 Return the intersection of two sets as a new set. 96 97 (i.e. all elements that are in both sets.) 98 """ 99 pass 100 101 def intersection_update(self, *args, **kwargs): # real signature unknown 102 """取交集并更更新到A中 103 >>> a = {'nick','jenny','suo'} 104 >>> b = {'nick','jenny','The knife girl'} 105 >>> a.intersection_update(b) 106 >>> a 107 {'jenny', 'nick'} 108 """ 109 """ Update a set with the intersection of itself and another. """ 110 pass 111 112 def isdisjoint(self, *args, **kwargs): # real signature unknown 113 """如果没有交集,返回True,否则返回False 114 >>> a = {'nick','jenny','suo'} 115 >>> b = {'nick','jenny','The knife girl'} 116 >>> a.isdisjoint(b) 117 False 118 """ 119 """ Return True if two sets have a null intersection. """ 120 pass 121 122 def issubset(self, *args, **kwargs): # real signature unknown 123 """是否是子序列 124 >>> a = {'nick','jenny','suo'} 125 >>> b = {'nick','jenny'} 126 >>> b.issubset(a) 127 True 128 >>> a.issubset(b) 129 False 130 """ 131 """ Report whether another set contains this set. """ 132 pass 133 134 def issuperset(self, *args, **kwargs): # real signature unknown 135 """是否是父序列 136 >>> a = {'nick','jenny','suo'} 137 >>> b = {'nick','jenny'} 138 >>> a.issuperset(b) 139 True 140 >>> b.issuperset(a) 141 False 142 """ 143 """ Report whether this set contains another set. """ 144 pass 145 146 def pop(self, *args, **kwargs): # real signature unknown 147 """移除元素 148 >>> a = {'nick','jenny','suo'} 149 >>> a.pop() 150 'suo' 151 >>> a 152 {'jenny', 'nick'} 153 """ 154 """ 155 Remove and return an arbitrary set element. 156 Raises KeyError if the set is empty. 157 """ 158 pass 159 160 def remove(self, *args, **kwargs): # real signature unknown 161 """移除指定元素,不存在报错 162 >>> a = {'nick','jenny','suo'} 163 >>> a.remove('nick') 164 >>> a 165 {'suo', 'jenny'} 166 >>> a.remove('The knife girl') 167 Traceback (most recent call last): 168 File "<stdin>", line 1, in <module> 169 KeyError: 'The knife girl' 170 >>> 171 """ 172 """ 173 Remove an element from a set; it must be a member. 174 175 If the element is not a member, raise a KeyError. 176 """ 177 pass 178 179 def symmetric_difference(self, *args, **kwargs): # real signature unknown 180 """对称交集 181 >>> a = {'nick','jenny','suo'} 182 >>> b = {'nick','jenny','The knife girl'} 183 >>> a.symmetric_difference(b) 184 {'suo', 'The knife girl'} 185 """ 186 """ 187 Return the symmetric difference of two sets as a new set. 188 189 (i.e. all elements that are in exactly one of the sets.) 190 """ 191 pass 192 193 def symmetric_difference_update(self, *args, **kwargs): # real signature unknown 194 """对称交集,并更新到a中 195 >>> a = {'nick','jenny','suo'} 196 >>> b = {'nick','jenny','The knife girl'} 197 >>> a.symmetric_difference_update(b) 198 >>> a 199 {'suo', 'The knife girl'} 200 """ 201 """ Update a set with the symmetric difference of itself and another. """ 202 pass 203 204 def union(self, *args, **kwargs): # real signature unknown 205 """并集 206 >>> a = {'nick','jenny','suo'} 207 >>> b = {'nick','jenny','The knife girl'} 208 >>> a.union(b) 209 {'suo', 'jenny', 'nick', 'The knife girl'} 210 """ 211 """ 212 Return the union of sets as a new set. 213 214 (i.e. all elements that are in either set.) 215 """ 216 pass 217 218 def update(self, *args, **kwargs): # real signature unknown 219 """更新 220 >>> a = {'nick','jenny','suo'} 221 >>> b = {'nick','jenny','The knife girl'} 222 >>> a.update(b) 223 >>> a 224 {'suo', 'jenny', 'nick', 'The knife girl'} 225 >>> b 226 {'jenny', 'nick', 'The knife girl'} 227 """ 228 """ Update a set with the union of itself and others. """ 229 pass 230 231 def __and__(self, *args, **kwargs): # real signature unknown 232 """ Return self&value. """ 233 pass 234 235 def __contains__(self, y): # real signature unknown; restored from __doc__ 236 """ x.__contains__(y) <==> y in x. """ 237 pass 238 239 def __eq__(self, *args, **kwargs): # real signature unknown 240 """ Return self==value. """ 241 pass 242 243 def __getattribute__(self, *args, **kwargs): # real signature unknown 244 """ Return getattr(self, name). """ 245 pass 246 247 def __ge__(self, *args, **kwargs): # real signature unknown 248 """ Return self>=value. """ 249 pass 250 251 def __gt__(self, *args, **kwargs): # real signature unknown 252 """ Return self>value. """ 253 pass 254 255 def __iand__(self, *args, **kwargs): # real signature unknown 256 """ Return self&=value. """ 257 pass 258 259 def __init__(self, seq=()): # known special case of set.__init__ 260 """ 261 set() -> new empty set object 262 set(iterable) -> new set object 263 264 Build an unordered collection of unique elements. 265 # (copied from class doc) 266 """ 267 pass 268 269 def __ior__(self, *args, **kwargs): # real signature unknown 270 """ Return self|=value. """ 271 pass 272 273 def __isub__(self, *args, **kwargs): # real signature unknown 274 """ Return self-=value. """ 275 pass 276 277 def __iter__(self, *args, **kwargs): # real signature unknown 278 """ Implement iter(self). """ 279 pass 280 281 def __ixor__(self, *args, **kwargs): # real signature unknown 282 """ Return self^=value. """ 283 pass 284 285 def __len__(self, *args, **kwargs): # real signature unknown 286 """ Return len(self). """ 287 pass 288 289 def __le__(self, *args, **kwargs): # real signature unknown 290 """ Return self<=value. """ 291 pass 292 293 def __lt__(self, *args, **kwargs): # real signature unknown 294 """ Return self<value. """ 295 pass 296 297 @staticmethod # known case of __new__ 298 def __new__(*args, **kwargs): # real signature unknown 299 """ Create and return a new object. See help(type) for accurate signature. """ 300 pass 301 302 def __ne__(self, *args, **kwargs): # real signature unknown 303 """ Return self!=value. """ 304 pass 305 306 def __or__(self, *args, **kwargs): # real signature unknown 307 """ Return self|value. """ 308 pass 309 310 def __rand__(self, *args, **kwargs): # real signature unknown 311 """ Return value&self. """ 312 pass 313 314 def __reduce__(self, *args, **kwargs): # real signature unknown 315 """ Return state information for pickling. """ 316 pass 317 318 def __repr__(self, *args, **kwargs): # real signature unknown 319 """ Return repr(self). """ 320 pass 321 322 def __ror__(self, *args, **kwargs): # real signature unknown 323 """ Return value|self. """ 324 pass 325 326 def __rsub__(self, *args, **kwargs): # real signature unknown 327 """ Return value-self. """ 328 pass 329 330 def __rxor__(self, *args, **kwargs): # real signature unknown 331 """ Return value^self. """ 332 pass 333 334 def __sizeof__(self): # real signature unknown; restored from __doc__ 335 """ S.__sizeof__() -> size of S in memory, in bytes """ 336 pass 337 338 def __sub__(self, *args, **kwargs): # real signature unknown 339 """ Return self-value. """ 340 pass 341 342 def __xor__(self, *args, **kwargs): # real signature unknown 343 """ Return self^value. """ 344 pass 345 346 __hash__ = None
六、其他
1、for循环
用户按照顺序循环可迭代对象中的内容
name = ('nick','jenney') for i in name: print(i)
2、enumrate
为可迭代的对象添加序号
user_info = { "name":"nick", "age":18, "job":"pythoner" } for k,v in enumerate(user_info,1): print(k,v,user_info.get(v))
3、range和xrange
指定范围,生成指定的数字
#python 2.7 版本 print range(1, 10) # 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9] print range(1, 10, 2) # 结果:[1, 3, 5, 7, 9] print range(30, 0, -2) # 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2] #python 3.5 版本 a = range(10) print(a) #结果:range(0, 10)
4、编码与进制转换
- utf-8与gbk编码转换
utf-8 —> unicode(通过解码方法转换:decode) gbk —> unicode (通过解码方法转换:decode) unicode —> utf-8 (通过编码方法转换:encode) unicode —> gbk (通过编码方法转换:encode)
- 进制的转换
- 把字符串用进制表示出来
name = "小鱼" a = bytes(name,encoding='utf-8') print(a) for i in a: print(i,bin(i)) #输出结果(utf-8 三个字节表示一个汉字) b'xe7xb4xa2xe5xaex81' 231 0b11100111 180 0b10110100 162 0b10100010 229 0b11100101 174 0b10101110 129 0b10000001 b = bytes(name,encoding='gbk') print(b) for i in b: print(i,bin(i)) #输出结果(gbk 两个字节表示一个汉字) b'xcbxf7xc4xfe' 203 0b11001011 247 0b11110111 196 0b11000100 254 0b11111110
练习题:
1.练习题1-while循环输入 1 2 3 4 5 6 8 9 10
#!/usr/bin/env python # -*- coding:utf-8 -*- i = 0 while i < 10: i += 1 print(i)
2.练习题2-求1-100的所有数的和
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 i = 0 5 sun = 0 6 while i < 100: 7 i += 1 8 sun += i 9 print(sun)
3.练习题3-输出 1-100 内的所有奇数
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 i = 0 5 while i < 100: 6 i += 1 7 # print(i) 8 rem = i % 2 9 if rem == 1: 10 print(i)
4.练习题4-输出 1-100 内的所有偶数
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 i = 0 4 while i < 100: 5 i += 1 6 rem = i % 2 7 if rem == 0: 8 print(i)
5.练习题5-求1-2+3-4+5 ... 99的所有数的和
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 i = 0 4 sun = 0 5 while i < 99: 6 i += 1 7 # print(i) 8 rem = i % 2 9 if rem == 1: 10 sun += i 11 sun1 = sun 12 # print(sun1) 13 else: 14 sun += i 15 sun2 = sun 16 # print(sun2) 17 print(sun1) 18 print(sun2) 19 sun = sun1 - sun2 20 print(sun)
6.练习题6-用户登陆(三次机会重试)
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #http://www.cnblogs.com/zhaojingyu/p/7771955.html 4 bw = 0 5 cw = True 6 li = [{'username': 'alex', 'password': '123'}, 7 {'username': 'wusir', 'password': '456'}, 8 {'username': 'taibai', 'password': '789'}, 9 ] 10 while bw < 3 and cw: #定义两个条件 3:可以循环3次, cw 等于True(正) 两个条件同时成立 11 bw += 1 #每次自增1 12 name = input('请输入用户名:') 13 pwd = input('请输入密码:') 14 for i in li: #print(i) 打印出3个dict列表 15 if name == i['username'] and pwd == i['password']: #判断输入条件 16 print('欢迎您登录') 17 cw = False #当上面条件成立是改变cw为False 这个循环停止(while条件不成立), 18 if str(cw) == 'True': #因为True是关键字所以只能判断字符串是否相同,等于True则打印用户名或者密码错误 19 print('用户名或者密码错误') 20 if str(cw) == 'True': #这里的如果是True则表明上面while循环中输入(用户名或者密码错误) 21 print('输入超过三次错误,在给你一个选择' 'Y :重新输入,其他 :退出') 22 xz = input('请选择') 23 if xz == 'Y': 24 while bw < 6 and cw: #6是3+3,表明在给3次机会 ,while循环跟上面同理 25 bw += 1 26 # print(bw) 27 name = input('请输入用户名:') 28 pwd = input('请输入密码:') 29 for i in li: 30 if name == i['username'] and pwd == i['password']: 31 print('欢迎您登录') 32 cw = False 33 if str(cw) == 'True': 34 print('用户名或者密码错误') 35 if xz != 'Y': 36 print('臭不要脸的可以走了') 37 if bw == 6: #表明一个输入错误6次 38 print('臭不要脸的可以走了')