Melissa R
0
Q:

python get all substrings

# Python3 code to demonstrate working of 
# Get all substrings of string 
# Using list comprehension + string slicing 
  
# initializing string  
test_str = "Geeks"
  
# printing original string  
print("The original string is : " + str(test_str)) 
  
# Get all substrings of string 
# Using list comprehension + string slicing 
res = [test_str[i: j] for i in range(len(test_str)) 
          for j in range(i + 1, len(test_str) + 1)] 
  
# printing result  
print("All substrings of string are : " + str(res)) 
1
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
15
def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1: return
        yield start
        start += len(sub) # use start += 1 to find overlapping matches

list(find_all('spam spam spam spam', 'spam')) # [0, 5, 10, 15]
1

New to Communities?

Join the community