1 def add(x, y): 2 return x + y 3 4 # 等價於 5 6 add = lambda x, y: x + y 7 print(add(1, 2)) # 3
1 dic = {'a': 13, 'b': 3, 'c': 34} 2 print(max(dic,key=lambda x:dic[x]))
現有兩元組(('a'),('b')),(('c'),('d')), 請使用python中匿名函數生成列表[{'a':'c'},{'b':'d'}]html
1 ret = zip((('a'),('b')),(('c'),('d'))) 2 res = map(lambda tup:{tup[0]:tup[1]},ret) 3 print(list(res))
寫出下列代碼輸出結果python
1 def multipliers(): 2 return [lambda x: i * x for i in range(4)] 3 # 返回3個匿名函數,到執行時i的值已爲3 4 print([m(2) for m in multipliers()]) 5 # result: 6 # [6, 6, 6, 6]
轉布爾類型git
1 print(bool([])) # False 2 print(bool('')) # False 3 print(bool(0)) # False 4 print(bool({})) # False 5 print(bool(())) # False
轉整形面試
1 print(int('3')) # 3
轉浮點型api
1 print(float('3')) # 3.0
轉複數類型數組
1 print(complex('3')) # (3+0j)
轉二進制數據結構
1 print(bin(2)) # 0b10
轉八進制app
1 print(oct(2)) # 0o2
轉十六進制less
1 print(hex(2)) # 0x2
絕對值ssh
1 print(abs(-3)) # 3
除餘
1 print(divmod(9, 4)) # (2, 1) 商2餘1
精確小數位
1 print(round(3.5687789,3)) # 3.569
冪運算
1 print(pow(2,3)) # 8
求和
1 print(sum([2,3])) # 5
最大值
1 print(max([2,3])) # 3
最小值
1 print(min([2,3])) # 2
轉列表類型
1 print(list((1,2,3))) # [1, 2, 3]
轉元組類型
1 print(tuple([1,2,3])) # (1, 2, 3)
轉字典類型
1 print(dict({1:'a',2:'b'})) # {1: 'a', 2: 'b'}
轉集合類型
1 print(set([1,1,2,3,3])) # {1, 2, 3}
轉不可變集合類型
1 only_read_set = frozenset([1, 1, 2, 3, 3]); 2 print(only_read_set) # frozenset({1, 2, 3}) 3 only_read_set[1] = 4 # TypeError: 'frozenset' object does not support item assignment
轉字符串
1 print(str(123)) # 123
1.將一個數值進行格式化顯示
2.若是參數format_spec未提供,則和調用str()效果相同
3.對於不一樣的類型,參數format_spec可提供的值都不同
1 print(format(3.1415926)) # 3.1415926 2 # 字符串:指定對齊方式,<是左對齊, >是右對齊,^是居中對齊 3 print(format('format', '<20')) 4 print(format('format', '>20')) 5 print(format('format', '^20')) 6 # result: 7 # format 8 # format 9 # format 10 11 # 整形: 12 # 轉換成二進制 13 print(format(3, 'b')) # 11 14 # 轉換unicode成字符 15 print(format(97, 'c')) # a 16 # 轉換成10進制 17 print(format(11, 'd')) # 11 18 # 轉換成8進制 19 print(format(11, 'o')) # 13 20 # 轉換成16進制 小寫字母表示 21 print(format(11, 'x')) # b 22 # 轉換成16進制 大寫字母表示 23 print(format(11, 'X')) # B 24 # 和d同樣 25 print(format(11, 'n')) # 11 26 # 默認和d同樣 27 print(format(11)) # 11 28 29 # 浮點型: 30 # 科學計數法,默認保留6位小數 31 print(format(314159267, 'e')) # '3.141593e+08' 32 # 科學計數法,指定保留2位小數 33 print(format(314159267, '0.2e')) # '3.14e+08' 34 # 科學計數法,指定保留2位小數,採用大寫E表示 35 print(format(314159267, '0.2E')) # '3.14E+08' 36 # 小數點計數法,默認保留6位小數 37 print(format(314159267, 'f')) # '314159267.000000' 38 # 小數點計數法,默認保留6位小數 39 print(format(3.14159267000, 'f')) # '3.141593' 40 ##小數點計數法,指定保留8位小數 41 print(format(3.14159267000, '0.8f')) # '3.14159267' 42 # 小數點計數法,指定保留10位小數 43 print(format(3.14159267000, '0.10f')) # '3.1415926700' 44 # 小數點計數法,無窮大轉換成大小字母 45 print(format(3.14e+1000000, 'F')) # 'INF'
轉字節
1 print(bytes('aaa', 'utf8')) # b'aaa' 2 print('aaa'.encode('utf8')) # b'aaa'
轉字節數組
1 print(bytearray('aaa', 'utf8')) # bytearray(b'aaa') 2 for i in bytearray('aaa', 'utf8'): 3 print(i) 4 # 97 5 # 97 6 # 97
查看bytes內存地址
1 print(memoryview(bytes('a', 'utf8'))) # <memory at 0x000000000272A588>
字符按unicode轉數字
1 print(ord('a')) # 97
數字按unicode轉字符
1 print(chr(97)) # 'a'
轉ascii碼
1 # 只要是ascii碼中的內容,就原樣輸出,不是就轉換成\u格式 2 print(ascii('張三')) # '\u5f20\u4e09'
將一個對象以字符串形式返回
1 print('hello%r' % 'world') # hello'world' 2 print(repr('1')) # '1' 3 print(repr([1, 2, 3])) # [1, 2, 3]
返回可迭代對象長度
1 print(len([1, 1, 1])) # 3 2 print(len('111')) # 3 3 print(len({1: 'a', 2: 'b', 3: 'c'})) # 3
枚舉化
1 print(list(enumerate(['a', 'b', 'c']))) # [(0, 'a'), (1, 'b'), (2, 'c')]
全部值都爲True則返回True,不然返回False
1 print(all([True, '', 1])) # False
存在一個值爲True則返回True,不然返回False
1 print(any([True, False, 0, ''])) # True
拉鍊方法,返回一個迭代器
1 num_list = [1, 2, 3] 2 letter_list = ['a', 'b', 'c'] 3 print(zip(num_list, letter_list)) # <zip object at 0x00000000021DB648> 4 print(list(zip(num_list, letter_list))) # [(1, 'a'), (2, 'b'), (3, 'c')]
過濾
1 # 篩選num_list裏的奇數 2 num_list = [1, 2, 3, 4, 5, 6] 3 result_list = filter(lambda i: i % 2 == 1, num_list) 4 print(list(result_list)) # [1, 3, 5] 5 # 等價於 6 print(list(i for i in num_list if i % 2 == 1)) # [1, 3, 5]
映射
1 # 取列表中每一個數的平方 2 num_list = [1, 2, 3, 4, 5, 6] 3 print(list(map(lambda i: i ** 2, num_list))) # [1, 4, 9, 16, 25, 36]
排序
1 num_list = [-1, -2, 3, -4] 2 # 默認排序 3 print(sorted(num_list)) # [-4, -2, -1, 3] 4 # 以列表中數字的絕對值升序 5 print(sorted(num_list, key=abs)) # [-1, -2, 3, -4] 6 # 以列表中數字的絕對值降序 7 print(sorted(num_list, key=abs, reverse=True)) # [-4, 3, -2, -1]
定義類方法
1 class A: 2 @classmethod 3 def print(self): 4 print('from A') 5 6 7 A.print() # from A
定義靜態方法
1 class A: 2 @staticmethod 3 def print(): 4 print('from A') 5 6 7 A.print() # from A
將方法包裝成屬性
1 class Person: 2 def __init__(self, name, age): 3 self.__name = name 4 self.__age = age 5 6 @property 7 def name(self): 8 return self.__name 9 10 @name.setter 11 def name(self, new_name): 12 self.__name = new_name 13 14 @name.deleter 15 def name(self): 16 print('執行刪除name操做') 17 18 19 p = Person('張三', 18) 20 print(p.name) # 張三 21 p.name = '李四' 22 print(p.name) # 李四 23 # 只是觸發對應deleter裝飾的函數,具體操做需在函數類完成 24 del p.name # 執行刪除name操做 25 print(p.name) # 李四
判斷一個對象是否是指定類的實例
1 class A: pass 2 3 class B: pass 4 5 a = A() 6 print(isinstance(a, A)) # True 7 8 print(isinstance(a, B)) # False
判斷一個類指定類的子類
1 class A: pass 2 3 class B(A): pass 4 5 class C: pass 6 7 print(issubclass(B, A)) # True 8 print(issubclass(B, C)) # False
全部類的基類
1 class A: pass 2 3 class B(A): pass 4 5 class C: pass 6 7 print(issubclass(A, object)) # True 8 print(issubclass(B, object)) # True 9 print(issubclass(C, object)) # True
獲取父類
1 class A: 2 @classmethod 3 def func(self): 4 print('print in A') 5 6 class B(A): 7 @classmethod 8 def func(self): 9 super().func() 10 super(B, self).func() 11 print('print in B') 12 13 B.func() 14 15 # result: 16 # print in A 17 # print in A 18 # print in B
將當前函數塊的全部變量以字典類型返回
1 a = 1 2 def outer(): 3 a = 2 4 def inner(): 5 b = 3 6 print(locals()) 7 inner() 8 9 outer() 10 # result 11 # {'b': 3}
將全局變量以字典類型返回
1 a = 1 2 def outer(): 3 a = 2 4 def inner(): 5 b = 3 6 print(globals()) 7 inner() 8 9 outer() 10 # result 11 # {'__name__': '__main__', '__doc__': None, '__package__': None, ..., 'a': 1, 'outer': <function outer at 0x000000000203C268>}
返回指定區間數字生成器
1 for i in range(1, 4): 2 print(i) 3 # result: 4 # 1 5 # 2 6 # 3
傳入可迭代對象返回迭代器
1 print(iter(range(1, 4))) # <range_iterator object at 0x0000000002792470>
迭代器取下一個值
1 range_iter = iter(range(1, 3)) 2 print(range_iter.__next__()) # 1 3 print(range_iter.__next__()) # 2 4 print(range_iter.__next__()) # StopIteration 取不到值拋異常
執行且有返回值
1 print(eval('1+1')) # 2
執行無返回值
1 print(exec('1+1')) # None
返回字符串編譯後字節代碼對象
1 str = "for i in range(0,10): print(i)" 2 c = compile(str, '', 'exec') # 編譯爲字節代碼對象 3 exec(c) 4 # result: 5 # 1 6 # 2 7 # 3 8 # 4 9 # 5 10 # 6 11 # 7 12 # 8 13 # 9 14 str = "3 * 4 + 5" 15 a = compile(str, '', 'eval') 16 print(eval(a)) # 17
判斷指定類或實例是否擁有指定屬性
1 class Person: 2 gender = '男' 3 4 def __init__(self, name, age): 5 self.name = name 6 self.age = age 7 8 9 # 判斷Person的實例p是否擁有name屬性 10 p = Person('張三', '李四') 11 print(hasattr(p, 'name')) # True 12 # 判斷Person類是否擁有name屬性 13 print(hasattr(Person, 'name')) # False 14 # 判斷Person類是否擁有gender屬性 15 print(hasattr(Person, 'gender')) # True
獲取指定類或實例的指定屬性引用
1 class Person: 2 gender = '男' 3 4 def __init__(self, name, age): 5 self.name = name 6 self.age = age 7 8 def show_name(self): 9 print(self.name) 10 11 12 p = Person('張三', 18) 13 # 獲取實例的屬性 14 print(getattr(p, 'age')) 15 # 獲取實例的方法 16 getattr(p, 'show_name')()
給指定類或對象的屬性賦值,沒有則建立後再賦值
1 class Person: 2 def __init__(self, name, age): 3 self.name = name 4 self.age = age 5 6 def show_name(self): 7 print(self.name) 8 9 10 print(hasattr(Person, 'gender')) # False 默認沒有gender屬性 11 setattr(Person, 'gender', '男') 12 print(hasattr(Person, 'gender')) # True
刪除指定類或對象的指定屬性
1 class Person: 2 gender = '男' 3 4 def __init__(self, name, age): 5 self.name = name 6 self.age = age 7 8 def show_name(self): 9 print(self.name) 10 11 12 print(hasattr(Person, 'gender')) # True 13 delattr(Person, 'gender') 14 print(hasattr(Person, 'gender')) # False
以字符串類型返回輸入值
1 >>> input('input your name:') 2 input your name:zhangsan 3 'zhangsan'
輸出
1 >>> print('hello world') 2 hello world
返回對象在內存中的哈希標識
1 print(hash('a')) # -1985915095439783199
返回對象在內存中的地址標識
1 print(id('a')) # 34187784
具體見文件操做
模塊導入
1 time =__import__('time')# 等價於 import time 2 print(time.time())
判斷對象是否可調用,返回True或False
1 def func(): 2 return 1 + 1 3 4 a = 1 5 print(callable(a)) # False 6 a = func 7 print(callable(a)) # True
返回類型的幫助信息
1 print(help(str)) 2 # result: 3 # class str(object) 4 # | str(object='') -> str 5 # | str(bytes_or_buffer[, encoding[, errors]]) -> str 6 # | 7 # | Create a new string object from the given object. If encoding or 8 # | errors is specified, then the object must expose a data buffer 9 # | that will be decoded using the given encoding and error handler. 10 # | Otherwise, returns the result of object.__str__() (if defined) 11 # | or repr(object). 12 # | encoding defaults to sys.getdefaultencoding(). 13 # | errors defaults to 'strict'. 14 # | 15 # | Methods defined here: 16 # | 17 # | __add__(self, value, /) 18 # | Return self+value. 19 # | 20 # | __contains__(self, key, /) 21 # | Return key in self. 22 # | 23 # | __eq__(self, value, /) 24 # | Return self==value. 25 # | 26 # | __format__(self, format_spec, /) 27 # | Return a formatted version of the string as described by format_spec. 28 # | 29 # | __ge__(self, value, /) 30 # | Return self>=value. 31 # | 32 # | __getattribute__(self, name, /) 33 # | Return getattr(self, name). 34 # | 35 # | __getitem__(self, key, /) 36 # | Return self[key]. 37 # | 38 # | __getnewargs__(...) 39 # | 40 # | __gt__(self, value, /) 41 # | Return self>value. 42 # | 43 # | __hash__(self, /) 44 # | Return hash(self). 45 # | 46 # | __iter__(self, /) 47 # | Implement iter(self). 48 # | 49 # | __le__(self, value, /) 50 # | Return self<=value. 51 # | 52 # | __len__(self, /) 53 # | Return len(self). 54 # | 55 # | __lt__(self, value, /) 56 # | Return self<value. 57 # | 58 # | __mod__(self, value, /) 59 # | Return self%value. 60 # | 61 # | __mul__(self, value, /) 62 # | Return self*value. 63 # | 64 # | __ne__(self, value, /) 65 # | Return self!=value. 66 # | 67 # | __repr__(self, /) 68 # | Return repr(self). 69 # | 70 # | __rmod__(self, value, /) 71 # | Return value%self. 72 # | 73 # | __rmul__(self, value, /) 74 # | Return value*self. 75 # | 76 # | __sizeof__(self, /) 77 # | Return the size of the string in memory, in bytes. 78 # | 79 # | __str__(self, /) 80 # | Return str(self). 81 # | 82 # | capitalize(self, /) 83 # | Return a capitalized version of the string. 84 # | 85 # | More specifically, make the first character have upper case and the rest lower 86 # | case. 87 # | 88 # | casefold(self, /) 89 # | Return a version of the string suitable for caseless comparisons. 90 # | 91 # | center(self, width, fillchar=' ', /) 92 # | Return a centered string of length width. 93 # | 94 # | Padding is done using the specified fill character (default is a space). 95 # | 96 # | count(...) 97 # | S.count(sub[, start[, end]]) -> int 98 # | 99 # | Return the number of non-overlapping occurrences of substring sub in 100 # | string S[start:end]. Optional arguments start and end are 101 # | interpreted as in slice notation. 102 # | 103 # | encode(self, /, encoding='utf-8', errors='strict') 104 # | Encode the string using the codec registered for encoding. 105 # | 106 # | encoding 107 # | The encoding in which to encode the string. 108 # | errors 109 # | The error handling scheme to use for encoding errors. 110 # | The default is 'strict' meaning that encoding errors raise a 111 # | UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 112 # | 'xmlcharrefreplace' as well as any other name registered with 113 # | codecs.register_error that can handle UnicodeEncodeErrors. 114 # | 115 # | endswith(...) 116 # | S.endswith(suffix[, start[, end]]) -> bool 117 # | 118 # | Return True if S ends with the specified suffix, False otherwise. 119 # | With optional start, test S beginning at that position. 120 # | With optional end, stop comparing S at that position. 121 # | suffix can also be a tuple of strings to try. 122 # | 123 # | expandtabs(self, /, tabsize=8) 124 # | Return a copy where all tab characters are expanded using spaces. 125 # | 126 # | If tabsize is not given, a tab size of 8 characters is assumed. 127 # | 128 # | find(...) 129 # | S.find(sub[, start[, end]]) -> int 130 # | 131 # | Return the lowest index in S where substring sub is found, 132 # | such that sub is contained within S[start:end]. Optional 133 # | arguments start and end are interpreted as in slice notation. 134 # | 135 # | Return -1 on failure. 136 # | 137 # | format(...) 138 # | S.format(*args, **kwargs) -> str 139 # | 140 # | Return a formatted version of S, using substitutions from args and kwargs. 141 # | The substitutions are identified by braces ('{' and '}'). 142 # | 143 # | format_map(...) 144 # | S.format_map(mapping) -> str 145 # | 146 # | Return a formatted version of S, using substitutions from mapping. 147 # | The substitutions are identified by braces ('{' and '}'). 148 # | 149 # | index(...) 150 # | S.index(sub[, start[, end]]) -> int 151 # | 152 # | Return the lowest index in S where substring sub is found, 153 # | such that sub is contained within S[start:end]. Optional 154 # | arguments start and end are interpreted as in slice notation. 155 # | 156 # | Raises ValueError when the substring is not found. 157 # | 158 # | isalnum(self, /) 159 # | Return True if the string is an alpha-numeric string, False otherwise. 160 # | 161 # | A string is alpha-numeric if all characters in the string are alpha-numeric and 162 # | there is at least one character in the string. 163 # | 164 # | isalpha(self, /) 165 # | Return True if the string is an alphabetic string, False otherwise. 166 # | 167 # | A string is alphabetic if all characters in the string are alphabetic and there 168 # | is at least one character in the string. 169 # | 170 # | isascii(self, /) 171 # | Return True if all characters in the string are ASCII, False otherwise. 172 # | 173 # | ASCII characters have code points in the range U+0000-U+007F. 174 # | Empty string is ASCII too. 175 # | 176 # | isdecimal(self, /) 177 # | Return True if the string is a decimal string, False otherwise. 178 # | 179 # | A string is a decimal string if all characters in the string are decimal and 180 # | there is at least one character in the string. 181 # | 182 # | isdigit(self, /) 183 # | Return True if the string is a digit string, False otherwise. 184 # | 185 # | A string is a digit string if all characters in the string are digits and there 186 # | is at least one character in the string. 187 # | 188 # | isidentifier(self, /) 189 # | Return True if the string is a valid Python identifier, False otherwise. 190 # | 191 # | Use keyword.iskeyword() to test for reserved identifiers such as "def" and 192 # | "class". 193 # | 194 # | islower(self, /) 195 # | Return True if the string is a lowercase string, False otherwise. 196 # | 197 # | A string is lowercase if all cased characters in the string are lowercase and 198 # | there is at least one cased character in the string. 199 # | 200 # | isnumeric(self, /) 201 # | Return True if the string is a numeric string, False otherwise. 202 # | 203 # | A string is numeric if all characters in the string are numeric and there is at 204 # | least one character in the string. 205 # | 206 # | isprintable(self, /) 207 # | Return True if the string is printable, False otherwise. 208 # | 209 # | A string is printable if all of its characters are considered printable in 210 # | repr() or if it is empty. 211 # | 212 # | isspace(self, /) 213 # | Return True if the string is a whitespace string, False otherwise. 214 # | 215 # | A string is whitespace if all characters in the string are whitespace and there 216 # | is at least one character in the string. 217 # | 218 # | istitle(self, /) 219 # | Return True if the string is a title-cased string, False otherwise. 220 # | 221 # | In a title-cased string, upper- and title-case characters may only 222 # | follow uncased characters and lowercase characters only cased ones. 223 # | 224 # | isupper(self, /) 225 # | Return True if the string is an uppercase string, False otherwise. 226 # | 227 # | A string is uppercase if all cased characters in the string are uppercase and 228 # | there is at least one cased character in the string. 229 # | 230 # | join(self, iterable, /) 231 # | Concatenate any number of strings. 232 # | 233 # | The string whose method is called is inserted in between each given string. 234 # | The result is returned as a new string. 235 # | 236 # | Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs' 237 # | 238 # | ljust(self, width, fillchar=' ', /) 239 # | Return a left-justified string of length width. 240 # | 241 # | Padding is done using the specified fill character (default is a space). 242 # | 243 # | lower(self, /) 244 # | Return a copy of the string converted to lowercase. 245 # | 246 # | lstrip(self, chars=None, /) 247 # | Return a copy of the string with leading whitespace removed. 248 # | 249 # | If chars is given and not None, remove characters in chars instead. 250 # | 251 # | partition(self, sep, /) 252 # | Partition the string into three parts using the given separator. 253 # | 254 # | This will search for the separator in the string. If the separator is found, 255 # | returns a 3-tuple containing the part before the separator, the separator 256 # | itself, and the part after it. 257 # | 258 # | If the separator is not found, returns a 3-tuple containing the original string 259 # | and two empty strings. 260 # | 261 # | replace(self, old, new, count=-1, /) 262 # | Return a copy with all occurrences of substring old replaced by new. 263 # | 264 # | count 265 # | Maximum number of occurrences to replace. 266 # | -1 (the default value) means replace all occurrences. 267 # | 268 # | If the optional argument count is given, only the first count occurrences are 269 # | replaced. 270 # | 271 # | rfind(...) 272 # | S.rfind(sub[, start[, end]]) -> int 273 # | 274 # | Return the highest index in S where substring sub is found, 275 # | such that sub is contained within S[start:end]. Optional 276 # | arguments start and end are interpreted as in slice notation. 277 # | 278 # | Return -1 on failure. 279 # | 280 # | rindex(...) 281 # | S.rindex(sub[, start[, end]]) -> int 282 # | 283 # | Return the highest index in S where substring sub is found, 284 # | such that sub is contained within S[start:end]. Optional 285 # | arguments start and end are interpreted as in slice notation. 286 # | 287 # | Raises ValueError when the substring is not found. 288 # | 289 # | rjust(self, width, fillchar=' ', /) 290 # | Return a right-justified string of length width. 291 # | 292 # | Padding is done using the specified fill character (default is a space). 293 # | 294 # | rpartition(self, sep, /) 295 # | Partition the string into three parts using the given separator. 296 # | 297 # | This will search for the separator in the string, starting at the end. If 298 # | the separator is found, returns a 3-tuple containing the part before the 299 # | separator, the separator itself, and the part after it. 300 # | 301 # | If the separator is not found, returns a 3-tuple containing two empty strings 302 # | and the original string. 303 # | 304 # | rsplit(self, /, sep=None, maxsplit=-1) 305 # | Return a list of the words in the string, using sep as the delimiter string. 306 # | 307 # | sep 308 # | The delimiter according which to split the string. 309 # | None (the default value) means split according to any whitespace, 310 # | and discard empty strings from the result. 311 # | maxsplit 312 # | Maximum number of splits to do. 313 # | -1 (the default value) means no limit. 314 # | 315 # | Splits are done starting at the end of the string and working to the front. 316 # | 317 # | rstrip(self, chars=None, /) 318 # | Return a copy of the string with trailing whitespace removed. 319 # | 320 # | If chars is given and not None, remove characters in chars instead. 321 # | 322 # | split(self, /, sep=None, maxsplit=-1) 323 # | Return a list of the words in the string, using sep as the delimiter string. 324 # | 325 # | sep 326 # | The delimiter according which to split the string. 327 # | None (the default value) means split according to any whitespace, 328 # | and discard empty strings from the result. 329 # | maxsplit 330 # | Maximum number of splits to do. 331 # | -1 (the default value) means no limit. 332 # | 333 # | splitlines(self, /, keepends=False) 334 # | Return a list of the lines in the string, breaking at line boundaries. 335 # | 336 # | Line breaks are not included in the resulting list unless keepends is given and 337 # | true. 338 # | 339 # | startswith(...) 340 # | S.startswith(prefix[, start[, end]]) -> bool 341 # | 342 # | Return True if S starts with the specified prefix, False otherwise. 343 # | With optional start, test S beginning at that position. 344 # | With optional end, stop comparing S at that position. 345 # | prefix can also be a tuple of strings to try. 346 # | 347 # | strip(self, chars=None, /) 348 # | Return a copy of the string with leading and trailing whitespace remove. 349 # | 350 # | If chars is given and not None, remove characters in chars instead. 351 # | 352 # | swapcase(self, /) 353 # | Convert uppercase characters to lowercase and lowercase characters to uppercase. 354 # | 355 # | title(self, /) 356 # | Return a version of the string where each word is titlecased. 357 # | 358 # | More specifically, words start with uppercased characters and all remaining 359 # | cased characters have lower case. 360 # | 361 # | translate(self, table, /) 362 # | Replace each character in the string using the given translation table. 363 # | 364 # | table 365 # | Translation table, which must be a mapping of Unicode ordinals to 366 # | Unicode ordinals, strings, or None. 367 # | 368 # | The table must implement lookup/indexing via __getitem__, for instance a 369 # | dictionary or list. If this operation raises LookupError, the character is 370 # | left untouched. Characters mapped to None are deleted. 371 # | 372 # | upper(self, /) 373 # | Return a copy of the string converted to uppercase. 374 # | 375 # | zfill(self, width, /) 376 # | Pad a numeric string with zeros on the left, to fill a field of the given width. 377 # | 378 # | The string is never truncated. 379 # | 380 # | ---------------------------------------------------------------------- 381 # | Static methods defined here: 382 # | 383 # | __new__(*args, **kwargs) from builtins.type 384 # | Create and return a new object. See help(type) for accurate signature. 385 # | 386 # | maketrans(x, y=None, z=None, /) 387 # | Return a translation table usable for str.translate(). 388 # | 389 # | If there is only one argument, it must be a dictionary mapping Unicode 390 # | ordinals (integers) or characters to Unicode ordinals, strings or None. 391 # | Character keys will be then converted to ordinals. 392 # | If there are two arguments, they must be strings of equal length, and 393 # | in the resulting dictionary, each character in x will be mapped to the 394 # | character at the same position in y. If there is a third argument, it 395 # | must be a string, whose characters will be mapped to None in the result. 396 # 397 # None 398 #
以字符串列表返回對象類型的屬性及函數
1 print(dir( 2 'a')) # ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']