鸿蒙传说
我认为这和他们提到的参数,在那里可以提高代码的可读性,并消除你通过切片获得的复杂性。str.startswith()str.endswith()startendtext = "afoobarstring"part_to_check = "bar"position = 4# approach 1 (startswith)text.startswith(part_to_check, position)# approach 2 (slicing)text[position:position + len(part_to_check)] == part_to_check# approach 3 (startswith and slicing)text[position:].startswith(part_to_check)虽然这三种方法做大致相同的事情,但方法1比其他方法更容易阅读和理解(恕我直言)。在方法 2 中,您还必须计算字符串的结束位置,在方法 3 中,您还有字符串的副本(如方法 2 中所示)和与方法 1 中相同的函数调用。我怀疑这也会导致更好的时间测量结果:In [1]: import timeit In [2]: timeit.timeit('text="afoobarstring"; part_to_check = "bar"; position = 4; text.startswith(part_to_check, position)', number=10000000) Out[2]: 1.6531553190034174In [3]: timeit.timeit('text="afoobarstring"; part_to_check = "bar"; position = 4; text[position:position + len(part_to_check)] == part_to_check', number=10000000) Out[3]: 1.8180583719986316In [4]: timeit.timeit('text="afoobarstring"; part_to_check = "bar"; position = 4; text[position:].startswith(part_to_check)', number=10000000)Out[4]: 2.349334787999396而且我认为方法1更干净,也是在引擎盖下:In [1]: import dis In [2]: def startswith(): ...: text="afoobarstring" ...: part_to_check = "bar" ...: position = 4 ...: return text.startswith(part_to_check, position) ...: In [3]: def slicing(): ...: text="afoobarstring" ...: part_to_check = "bar" ...: position = 4 ...: return text[position:position + len(part_to_check)] == part_to_check ...: In [4]: def slicing_and_startswith(): ...: text="afoobarstring" ...: part_to_check = "bar" ...: position = 4 ...: return text[position:].startswith(part_to_check) ...: In [5]: dis.dis(startswith) 2 0 LOAD_CONST 1 ('afoobarstring') 3 STORE_FAST 0 (text) 3 6 LOAD_CONST 2 ('bar') 9 STORE_FAST 1 (part_to_check) 4 12 LOAD_CONST 3 (4) 15 STORE_FAST 2 (position) 5 18 LOAD_FAST 0 (text) 21 LOAD_ATTR 0 (startswith) 24 LOAD_FAST 1 (part_to_check) 27 LOAD_FAST 2 (position) 30 CALL_FUNCTION 2 (2 positional, 0 keyword pair) 33 RETURN_VALUEIn [6]: dis.dis(slicing) 2 0 LOAD_CONST 1 ('afoobarstring') 3 STORE_FAST 0 (text) 3 6 LOAD_CONST 2 ('bar') 9 STORE_FAST 1 (part_to_check) 4 12 LOAD_CONST 3 (4) 15 STORE_FAST 2 (position) 5 18 LOAD_FAST 0 (text) 21 LOAD_FAST 2 (position) 24 LOAD_FAST 2 (position) 27 LOAD_GLOBAL 0 (len) 30 LOAD_FAST 1 (part_to_check) 33 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 36 BINARY_ADD 37 BUILD_SLICE 2 40 BINARY_SUBSCR 41 LOAD_FAST 1 (part_to_check) 44 COMPARE_OP 2 (==) 47 RETURN_VALUEIn [7]: dis.dis(slicing_and_startswith) 2 0 LOAD_CONST 1 ('afoobarstring') 3 STORE_FAST 0 (text) 3 6 LOAD_CONST 2 ('bar') 9 STORE_FAST 1 (part_to_check) 4 12 LOAD_CONST 3 (4) 15 STORE_FAST 2 (position) 5 18 LOAD_FAST 0 (text) 21 LOAD_FAST 2 (position) 24 LOAD_CONST 0 (None) 27 BUILD_SLICE 2 30 BINARY_SUBSCR 31 LOAD_ATTR 0 (startswith) 34 LOAD_FAST 1 (part_to_check) 37 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 40 RETURN_VALUE我认为它与 -方法类似。这就是为什么我没有单独展示这个。endswith()