python方法
Posted lm0429
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python方法相关的知识,希望对你有一定的参考价值。
数字
int(整形)
先记住:
int:
n="11" m=int(n,base=2) print(m)
“11”当成二进制转换成十进制
bit_length():
n=11 m=n.bit_length() print(m)
当前数字至少用几位二进制来表示
class int(object): """ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object 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): """ 返回表示该数字的时占用的最少位数 """ """ int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) ‘0b100101‘ >>> (37).bit_length() """ return 0 def conjugate(self, *args, **kwargs): # real signature unknown """ 返回该复数的共轭复数 """ """ Returns self, the complex conjugate of any int. """ pass def __abs__(self): """ 返回绝对值 """ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): """ x.__add__(y) <==> x+y """ pass def __and__(self, y): """ x.__and__(y) <==> x&y """ pass def __cmp__(self, y): """ 比较两个数大小 """ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __coerce__(self, y): """ 强制生成一个元组 """ """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): """ 相除,得到商和余数组成的元组 """ """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): """ x.__div__(y) <==> x/y """ pass def __float__(self): """ 转换为浮点类型 """ """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): """ x.__floordiv__(y) <==> x//y """ pass def __format__(self, *args, **kwargs): # real signature unknown pass def __getattribute__(self, name): """ x.__getattribute__(‘name‘) <==> x.name """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown """ 内部调用 __new__方法或创建对象时传入参数使用 """ pass def __hash__(self): """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。""" """ x.__hash__() <==> hash(x) """ pass def __hex__(self): """ 返回当前数的 十六进制 表示 """ """ x.__hex__() <==> hex(x) """ pass def __index__(self): """ 用于切片,数字无意义 """ """ x[y:z] <==> x[y.__index__():z.__index__()] """ pass def __init__(self, x, base=10): # known special case of int.__init__ """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ """ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object 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): """ 转换为整数 """ """ x.__int__() <==> int(x) """ pass def __invert__(self): """ x.__invert__() <==> ~x """ pass def __long__(self): """ 转换为长整数 """ """ x.__long__() <==> long(x) """ pass def __lshift__(self, y): """ x.__lshift__(y) <==> x<<y """ pass def __mod__(self, y): """ x.__mod__(y) <==> x%y """ pass def __mul__(self, y): """ x.__mul__(y) <==> x*y """ pass def __neg__(self): """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __nonzero__(self): """ x.__nonzero__() <==> x != 0 """ pass def __oct__(self): """ 返回改值的 八进制 表示 """ """ x.__oct__() <==> oct(x) """ pass def __or__(self, y): """ x.__or__(y) <==> x|y """ pass def __pos__(self): """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): """ 幂,次方 """ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): """ x.__radd__(y) <==> y+x """ pass def __rand__(self, y): """ x.__rand__(y) <==> y&x """ pass def __rdivmod__(self, y): """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): """转化为解释器可读取的形式 """ """ x.__repr__() <==> repr(x) """ pass def __str__(self): """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式""" """ x.__str__() <==> str(x) """ pass def __rfloordiv__(self, y): """ x.__rfloordiv__(y) <==> y//x """ pass def __rlshift__(self, y): """ x.__rlshift__(y) <==> y<<x """ pass def __rmod__(self, y): """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): """ x.__rmul__(y) <==> y*x """ pass def __ror__(self, y): """ x.__ror__(y) <==> y|x """ pass def __rpow__(self, x, z=None): """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rrshift__(self, y): """ x.__rrshift__(y) <==> y>>x """ pass def __rshift__(self, y): """ x.__rshift__(y) <==> x>>y """ pass def __rsub__(self, y): """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): """ x.__rtruediv__(y) <==> y/x """ pass def __rxor__(self, y): """ x.__rxor__(y) <==> y^x """ pass def __sub__(self, y): """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): """ x.__truediv__(y) <==> x/y """ pass def __trunc__(self, *args, **kwargs): """ 返回数值被截取为整形的值,在整形中无意义 """ pass def __xor__(self, y): """ x.__xor__(y) <==> x^y """ 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
字符串
主要方法:
join:
n=‘ABC‘ a=‘-‘ m=a.join(n) print(m) # 把一个字符串插入到括号中的字符串中去
split:
n=‘abcabcabc‘ m=n.split(‘a‘,3) p=n.rsplit(‘a‘,3) print(m) print(p) # 以一个字符串分割,可以限制分割几次,无法获取分割的字符串
find:
n=‘aBcAa‘ m=n.find(‘a‘,2,3) print(m) # 查找字符串所在的位置,可限制查找范围,没有显示-1
strip:
n=‘ABCDEF‘ m=n.lstrip(‘ABCEF‘) v=n.rstrip(‘ABCEF‘) p=n.strip(‘ABCEF‘) print(m) print(v) print(p) # 去除左or右or左右的字符串,去除的字符串可以是是括号中填入字符串子集,(与方向有关)(默认空格or换行符)
upper:
n=‘abc‘ m=n.upper() print(m) # 每个字母转换成大写
lower:
n=‘ABC‘ m=n.lower() print(m) # 每个字母转换成小写
replace:
n=‘AbcAbcAbc‘ m=n.replace(‘A‘,‘a‘,2) print(m) # 替换字符串,参数:老的,新的,次数
索引(下标):
n=‘abc‘ m=n[1] print(m) # 索引,下标,获取字符串中的某一字符
切片:
n=‘abc‘ m=n[0:2] print(m) # 切片,取一段字符串
len:
n=‘abc‘ m=len() print(m)n # 获取当前字符串中由几个字符
for :
n=‘abcdef‘ for m in n: print(m) # 每次输出一个字符 # for 变量名 in n: # print(变量名)
1 # str 2 3 # capitalize() 4 # n=‘abc‘ 5 # m=n.capitalize() 6 # print(m) 7 # 首字母大写 8 9 # casefold() 10 # n=‘aBc‘ 11 # m=n.casefold() 12 # print(m) 13 # 全部变成小写字母 14 15 # center() 16 # n=‘aBc‘ 17 # m=n.center(11,‘*‘) 18 # print(m) 19 # 文字居中,可添加填充符合,默认无 20 21 # count() 22 # n=‘aBcAa‘ 23 # m=n.count(‘a‘,3) 24 # print(m) 25 # 统计字符个数,后面限制统计前多少位 26 27 # endswith() 28 # n=‘aBcAa‘ 29 # m=n.endswith(‘Aa‘) 30 # print(m) 31 # 判断结尾字符串 32 33 # startswith() 34 # n=‘aBcAa‘ 35 # m=n.startswith(‘A‘) 36 # print(m) 37 # 判断首字符串 38 39 # expandtabs() 40 # n=‘aBc\tAa‘ 41 # m=n.expandtabs(10) 42 # print(m) 43 # 将\t转换成空客,输入n,每n个字符一组,碰到\t用空格补全一组 44 45 # find() 46 # n=‘aBcAa‘ 47 # m=n.find(‘a‘,2,3) 48 # print(m) 49 # 查找字符串所在的位置,可限制查找范围,没有显示-1 50 51 # format() 52 # n=‘AWBcQAa‘ 53 # m=n.format(W=‘w‘,Q=‘q‘) 54 # print(m) 55 # 将大括号里面的字符串代替:等号连接 56 # i=n.format_map("W":‘1‘,"Q":‘2‘) 57 # print(i) 58 # 将大括号里面的字符串代替:大括号,引号。冒号链接 59 60 # index() 61 # n=‘AWBcQAa‘ 62 # m=n.index(‘A‘) 63 # print(m) 64 # 查找字符串所在的位置,可限制查找范围,没有存在,程序报错 65 66 # isalnum() 67 # n=‘a1‘ 68 # m=n.isalnum() 69 # print(m) 70 # 判断是否只有数字或字母,True or False 71 72 # isalpha() 73 # n=‘aa啊‘ 74 # m=n.isalpha() 75 # print(m) 76 # 判断是否只有字母,汉字,True or False 77 78 # isascii() 79 # n=‘123‘ 80 # m=n.isascii() 81 # print(m) 82 # 如果字符串中的所有字符都是ASCII,则返回true,否则返回false。 83 84 # isdecimal() 85 # n=‘123‘ 86 # m=n.isdecimal() 87 # print(m) 88 # 如果字符串中的所有字符都是数字(只能是阿拉伯数字),则返回true,否则返回false 89 90 # isdigit() 91 # n=‘②‘ 92 # m=n.isdigit() 93 # print(m) 94 # 如果字符串中的所有字符都是数字(可以是阿拉伯数字也可以是①这种数字),则返回true,否则返回false 95 96 # isnumeric() 97 # n=‘②二‘ 98 # m=n.isnumeric() 99 # print(m) 100 # 如果字符串中的所有字符都是数字(可以是阿拉伯数字或者是①这种数字或者一二三三四),则返回true,否则返回false 101 102 # isidentifier() 103 # n=‘asd23‘ 104 # m=n.isidentifier() 105 # print(m) 106 # 如果字符串是有效的python标识符,不能数字开头,则返回true,否则返回false。使用keyword.iskeyword()测试保留的标识符,如“def”和“类(class)”。 107 108 # islower() 109 # n=‘asd23‘ 110 # m=n.islower() 111 # print(m) 112 # 如果字符串是小写字符串,则返回true,否则返回false 113 114 # isprintable() 115 # n=‘asd23\n‘ 116 # m=n.isprintable() 117 # print(m) 118 # 字符串中存在不可打印(看不见的:\n换行,\t空格)False。 119 120 # isspace() 121 # n=‘ ‘ 122 # m=n.isspace() 123 # print(m) 124 # 判断字符串是空格 125 126 # istitle() 127 # n=‘Abc Abc‘ 128 # m=n.istitle() 129 # print(m) 130 # 判断每个单词是否都是首字母大写 131 132 # isupper() 133 # n=‘ABC DEF‘ 134 # m=n.isupper() 135 # print(m) 136 # 判断每个字母是否都是大写 137 138 # join() 139 # n=‘ABC‘ 140 # a=‘-‘ 141 # m=a.join(n) 142 # print(m) 143 # 把一个字符串插入到括号中的字符串中去 144 145 # ljust()、rjust() 146 # n=‘ABC DEF‘ 147 # m=n.ljust(10,‘*‘) 148 # v=n.rjust(10,‘*‘) 149 # print(m) 150 # print(v) 151 # 左或者右填充字自定义符串 152 153 # zfill() 154 # n=‘ABC DEF‘ 155 # m=n.zfill(10) 156 # print(m) 157 # 左填充数字0 158 159 # lower() 160 # n=‘ABC DEF‘ 161 # m=n.lower() 162 # print(m) 163 # 转换成小写字母 164 165 #lstrip()、strip()、rstrip() 166 # n=‘ABCDEF‘ 167 # m=n.lstrip(‘ABCEF‘) 168 # v=n.rstrip(‘ABCEF‘) 169 # p=n.strip(‘ABCEF‘) 170 # print(m) 171 # print(v) 172 # print(p) 173 # 去除左or右or左右的字符串,去除的字符串可以是是括号中填入字符串子集,(与方向有关)(默认空格or换行符) 174 175 #maketrans()、translate() 176 # n=‘ABCDEF‘ 177 # m=‘abcdef‘ 178 # v=‘ABCdef‘ 179 # p=str.maketrans(n,m) 180 # k=v.translate(p) 181 # print(k) 182 # maketrans制作一个对应关系,translate使用这个关系进行替换 183 184 #partition()、rpartition()、split()、rsplit()、splitlines() 185 # n=‘abcabcabc‘ 186 # m=n.partition(‘ab‘) 187 # p=n.rpartition(‘ab‘) 188 # print(m) 189 # print(p) 190 # 以一个字符串分割成三份,可以获取分割的字符串 191 # n=‘abcabcabc‘ 192 # m=n.split(‘a‘,3) 193 # p=n.rsplit(‘a‘,3) 194 # print(m) 195 # print(p) 196 # 以一个字符串分割,可以限制分割几次,无法获取分割的字符串 197 # n=‘abc\nabc\nabc‘ 198 # m=n.splitlines(True) 199 # print(m) 200 # 以空格或空格符分割,可输入参数True 显示换行符 201 202 #swapcase() 203 # n=‘AbcAbcAbc‘ 204 # m=n.swapcase() 205 # print(m) 206 # 大小写转换 207 208 #replace() 209 # n=‘AbcAbcAbc‘ 210 # m=n.replace(‘A‘,‘a‘,2) 211 # print(m) 212 # 替换字符串,参数:老的,新的,次数 213 214 #upper() 215 # n=‘abc‘ 216 # m=n.upper() 217 # print(m) 218 # 每个字母转换成大写 219 220 #lower() 221 # n=‘ABC‘ 222 # m=n.lower() 223 # print(m) 224 # 每个字母转换成小写 225 226 #索引,下标 227 # n=‘abc‘ 228 # m=n[1] 229 # print(m) 230 # 索引,下标,获取字符串中的某一字符 231 232 #切片 233 # n=‘abc‘ 234 # m=n[0:2] 235 # print(m) 236 # 切片,取一段字符串 237 238 #len() 239 # n=‘abc‘ 240 # m=len() 241 # print(m)n 242 # 获取当前字符串中由几个字符 243 244 #for 245 # n=‘abcdef‘ 246 # for m in n: 247 # print(m) 248 # 每次输出一个字符 249 # for 变量名 in n: 250 # print(变量名)
系统
str
class str(basestring): """ str(object=‘‘) -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. """ def capitalize(self): """ 首字母变大写 """ """ S.capitalize() -> string Return a copy of the string S with only its first character capitalized. """ return "" def center(self, width, fillchar=None): """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """ """ S.center(width[, fillchar]) -> string 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): """ 子序列个数 """ """ 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 decode(self, encoding=None, errors=None): """ 解码 """ """ S.decode([encoding[,errors]]) -> object Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is ‘strict‘ meaning that encoding errors raise a UnicodeDecodeError. Other possible values are ‘ignore‘ and ‘replace‘ as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. """ return object() def encode(self, encoding=None, errors=None): """ 编码,针对unicode """ """ S.encode([encoding[,errors]]) -> object Encodes S using the codec registered for encoding. encoding defaults to the default encoding. 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 is able to handle UnicodeEncodeErrors. """ return object() def endswith(self, suffix, start=None, end=None): """ 是否以 xxx 结束 """ """ 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=None): """ 将tab转换成空格,默认一个tab转换成8个空格 """ """ S.expandtabs([tabsize]) -> string 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): """ 寻找子序列位置,如果没找到,返回 -1 """ """ S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def format(*args, **kwargs): # known special case of str.format """ 字符串格式化,动态参数,将函数式编程时细说 """ """ S.format(*args, **kwargs) -> string Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘‘ and ‘‘). """ pass def index(self, sub, start=None, end=None): """ 子序列位置,如果没找到,报错 """ S.index(sub [,start [,end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0 def isalnum(self): """ 是否是字母和数字 """ """ 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): """ 是否是字母 """ """ 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 isdigit(self): """ 是否是数字 """ """ 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 islower(self): """ 是否小写 """ """ 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 isspace(self): """ 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): """ S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): """ 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): """ 连接 """ """ S.join(iterable) -> string 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): """ 内容左对齐,右侧填充 """ """ S.ljust(width[, fillchar]) -> string Return S left-justified in a string of length width. Padding is done using the specified fill character (default is a space). """ return "" def lower(self): """ 变小写 """ """ S.lower() -> string Return a copy of the string S converted to lowercase. """ return "" def lstrip(self, chars=None): """ 移除左侧空白 """ """ S.lstrip([chars]) -> string or unicode Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ return "" def partition(self, sep): """ 分割,前,中,后三部分 """ """ 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): """ 替换 """ """ S.replace(old, new[, count]) -> string Return a copy of string 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): """ 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): """ 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): """ S.rjust(width[, fillchar]) -> string 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): """ 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=None): """ S.rsplit([sep [,maxsplit]]) -> list of strings Return a list of the words in the string 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 or is None, any whitespace string is a separator. """ return [] def rstrip(self, chars=None): """ S.rstrip([chars]) -> string or unicode Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ return "" def split(self, sep=None, maxsplit=None): """ 分割, maxsplit最多分割几次 """ """ S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in the string 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=False): """ 根据换行分割 """ """ S.splitlines(keepends=False) -> 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): """ 是否起始 """ """ 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): """ 移除两段空白 """ """ S.strip([chars]) -> string or unicode 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. If chars is unicode, S will be converted to unicode before stripping """ return "" def swapcase(self): """ 大写变小写,小写变大写 """ """ S.swapcase() -> string Return a copy of the string S with uppercase characters converted to lowercase and vice versa. """ return "" def title(self): """ S.title() -> string Return a titlecased version of S, i.e. words start with uppercase characters, all remaining cased characters have lowercase. """ return "" def translate(self, table, deletechars=None): """ 转换,需要先做一个对应表,最后一个表示删除字符集合 intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!" print str.translate(trantab, ‘xm‘) """ """ S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256 or None. If the table argument is None, no translation is applied and the operation simply removes the characters in deletechars. """ return "" def upper(self): """ S.upper() -> string Return a copy of the string S converted to uppercase. """ return "" def zfill(self, width): """方法返回指定长度的字符串,原字符串右对齐,前面填充0。""" """ S.zfill(width) -> string 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 _formatter_field_name_split(self, *args, **kwargs): # real signature unknown pass def _formatter_parser(self, *args, **kwargs): # real signature unknown pass def __add__(self, y): """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): """ x.__contains__(y) <==> y in x """ pass def __eq__(self, y): """ x.__eq__(y) <==> x==y """ pass def __format__(self, format_spec): """ S.__format__(format_spec) -> string Return a formatted version of S as described by format_spec. """ return "" def __getattribute__(self, name): """ x.__getattribute__(‘name‘) <==> x.name """ pass def __getitem__(self, y): """ x.__getitem__(y) <==> x[y] """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __getslice__(self, i, j): """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): """ x.__gt__(y) <==> x>y """ pass def __hash__(self): """ x.__hash__() <==> hash(x) """ pass def __init__(self, string=‘‘): # known special case of str.__init__ """ str(object=‘‘) -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. # (copied from class doc) """ pass def __len__(self): """ x.__len__() <==> len(x) """ pass def __le__(self, y): """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): """ x.__lt__(y) <==> x<y """ pass def __mod__(self, y): """ x.__mod__(y) <==> x%y """ pass def __mul__(self, n): """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): """ x.__repr__() <==> repr(x) """ pass def __rmod__(self, y): """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, n): """ x.__rmul__(n) <==> n*x """ pass def __sizeof__(self): """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __str__(self): """ x.__str__() <==> str(x) """ pass str
列表 list
1 # list 2 3 # append() 4 # n = [‘a‘,‘b‘,‘c‘,1,2,3] 5 # n.append(‘a‘) 6 # print(n) 7 # 在最后添加一个对象 8 9 # clear() 10 # n = [‘a‘,‘b‘,‘c‘,1,2,3] 11 # n.clear() 12 # print(n) 13 # 清空列表所有的对象 14 15 # copy() 16 # n = [‘a‘,‘b‘,‘c‘,1,2,3] 17 # m = n.copy() 18 # print(m) 19 # 复制一个列表(浅复制) 20 21 # count() 22 # n = [‘a‘,‘b‘,‘c‘,1,2,3,[1,2]] 23 # m = n.count(1) 24 # print(m) 25 # 统计列表中对象出现的次数 26 27 # extend() 28 # n = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] 29 # n.extend([1, 2]) 30 # print(n) 31 # 添加迭代对象,以for 变量 in n的样式添加 32 33 # index() 34 # n = [‘a‘, [1, 2], ‘b‘, ‘c‘, 1, ‘c‘, 2, 3] 35 # m = n.index(1) 36 # print(m) 37 # 查询对象所在的位置,从左边查起,只查询一个 38 39 # insert() 40 # n = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] 41 # n.insert(0, ‘q‘) 42 # print(n) 43 # 指定位置插入对象 44 45 # pop() 46 # n = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] 47 # m = n.pop(1) 48 # print(n) 49 # print(m) 50 # 根据索引删除一个对象,可以获取删除的对象,没写索引默认最后一个 51 52 # remove() 53 # n = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] 54 # n.remove(‘b‘) 55 # print(n) 56 # 根据对象的值删除列表中的对象 57 58 # reverse() 59 # n = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] 60 # n.reverse() 61 # print(n) 62 # 颠倒一个列表 63 64 # sort() 65 # n = [1, 2, 3] 66 # n.sort(reverse=True) 67 # print(n) 68 # 排序,默认从小到大排序 69 70 # list 另外方法 71 # 1.列表格式 72 73 # 2.列表可以嵌套任何类型 74 75 # 3.索引取值 76 # n = [‘a‘, ‘b‘, ‘c‘, 1, [7, 8], 2, 3] 77 # n = n[3] 78 # n = n[4][1] 79 # print(n) 80 81 82 # 4.切片取值 83 # n = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] 84 # n = n[1:3] 85 # print(n) 86 87 # 5.for 循环 88 # n = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] 89 # for m in n: 90 # print(m) 91 92 # 6.可修改,索引方式修改 93 # n = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] 94 # n[1] = ‘q‘ 95 # print(n) 96 97 # 7.删除(pop,remove,del(索引,切片),clear,) 98 # n = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] 99 # del n[1] 100 # print(n) 101 102 # 8,in操作 103 # n = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] 104 # m = ‘a‘ in n 105 # print(m) 106 # 判断对象是否在列表里 107 108 # 9.str转换成list,内部for循环 109 # n = ‘abc‘ 110 # n = list(n) 111 # print(n) 112 # list转换成str 用for循环 113 # n = [‘a‘, ‘b‘, ‘c‘] 114 # s = ‘‘ 115 # for m in n: 116 # s = s + str(m) 117 # print(s)
元祖 tuple
1 # tuple元祖元素不可被修改,不能增加或删除 2 # 元祖的一级元素不能被修改,嵌套列表时,列表里的元素可以修改 3 # 1.索引 4 # n = (‘a‘, ‘b‘, ‘c‘, 1, 2, 3,) 5 # m = n[2] 6 # print(m) 7 8 # 2.切片 9 # n = (‘a‘, ‘b‘, ‘c‘, 1, 2, 3,) 10 # m = n[2:5] 11 # print(m) 12 13 # 3.for 循环,可迭代对象 14 # n = (‘a‘, ‘b‘, ‘c‘, 1, 2, 3,) 15 # for m in n: 16 # print(m) 17 18 # 4.转换 19 # list转换 20 # n = (‘a‘, ‘b‘, ‘c‘, 1, 2, 3,) 21 # m = list(n) 22 # print(m) 23 # str转换 24 # n = (‘a‘, ‘b‘, ‘c‘, 1, 2, 3,) 25 # s = ‘‘ 26 # for m in n: 27 # s = s + str(m) 28 # print(s) 29 30 # count() 31 # n = (‘a‘, ‘b‘, ‘c‘, 1, 2, 3,) 32 # m = n.count(‘b‘) 33 # print(m) 34 # 统计对象出现的次数 35 36 # index() 37 # n = (‘a‘, ‘b‘, ‘c‘, 1, 2, 3,) 38 # m = n.index(‘b‘) 39 # print(m) 40 # 查询对象所在的位置
字典 dict
重要的:
# items()获取dict的key和values n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ m = n.items() print(m)
# values()获取dict的值 n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ m = n.values() print(m)
# keys()获取dict的key n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ m = n.keys() print(m)
# get()根据key获取value,key不存在时,可以指定返回值 n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ m = n.get(‘aa‘, ‘N‘) print(m)
1 # 字典 dict 2 3 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ ‘a‘是键(key),‘a1‘是值,‘a‘: ‘a1‘是一个键值对 4 5 # 列表,字典,不能做字典的键(key) 6 7 # 字典的值可以是任何值 8 9 # 字典是无序的 10 11 # 索引查找 12 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ 13 # m = n[‘a‘] 14 # print(m) 15 16 # 删除 17 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ 18 # del n[‘a‘] 19 # print(n) 20 21 # for 循环,输出的是key 22 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ 23 # for m in n: 24 # print(m) 25 26 # keys()获取dict的key 27 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ 28 # m = n.keys() 29 # print(m) 30 31 # values()获取dict的值 32 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ 33 # m = n.values() 34 # print(m) 35 36 # items()获取dict的key和values 37 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ 38 # m = n.items() 39 # print(m) 40 41 # clear()清空字典 42 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ 43 # n.clear() 44 # print(n) 45 46 # copy() 复制 47 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ 48 # m = n.copy() 49 # print(m) 50 51 # fromkeys() 根据序列创建字典,并指定统一的value 52 # n = dict.fromkeys([‘a‘, ‘b‘], 1) 53 # print(n) 54 55 # get()根据key获取value,key不存在时,可以指定返回值 56 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ 57 # m = n.get(‘aa‘, ‘N‘) 58 # print(m) 59 60 # pop() 删除,可以获取删除的键值对的值,key不存在时,可以指定返回值 61 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘ 62 # m = n.pop(‘aa‘, ‘N‘) 63 # print(n) 64 # print(m) 65 66 # popitem() 删除一个键值对,可以获取删除的键值对,无法输入参数 67 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘, ‘c‘: ‘c1‘, ‘d‘: ‘d1‘ 68 # m = n.popitem() 69 # print(n) 70 # print(m) 71 72 # setdefault() 设置键值对,已存在的不设置,返回已存在的值。不存在,添加设置的键值对,返回设置的值 73 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘, ‘c‘: ‘c1‘ 74 # m = n.setdefault(‘d‘,‘d1‘) 75 # print(n) 76 # print(m) 77 78 # update() 对字典进行更新,两种用法 79 # n = ‘a‘: ‘a1‘, ‘b‘: ‘b2‘, ‘c‘: ‘c1‘, ‘d‘: ‘d1‘ 80 # n.update(‘a‘: ‘a2‘, ‘b‘: ‘b2‘) 81 # n.update(a=‘a2‘, b=‘b2‘) 82 # print(n)
以上是关于python方法的主要内容,如果未能解决你的问题,请参考以下文章