w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How To Get All The Contiguous Substrings Of A String In Python?

The only improvement I could think of is, to use list comprehension like this

def get_all_substrings(input_string):
  length = len(input_string)
  return [input_string[i:j+1] for i in xrange(length) for j in

print get_all_substrings('abcde')

The timing comparison between, yours and mine

def get_all_substrings(string):
  length = len(string)
  alist = []
  for i in xrange(length):
    for j in xrange(i,length):
      alist.append(string[i:j + 1]) 
  return alist

def get_all_substrings_1(input_string):
  length = len(input_string)
  return [input_string[i:j + 1] for i in xrange(length) for j in

from timeit import timeit
print timeit("get_all_substrings('abcde')", "from __main__ import
# 3.33308315277
print timeit("get_all_substrings_1('abcde')", "from __main__ import
# 2.67816185951

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.