How To Count Substrings In A String With Python
I’m still working on the CodingBat Python exercises, and have found this problem a bit challenging to put into one line of code:
Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so “hixxxhi” yields 1 (we won’t count the end substring).
last2(‘hixxhi’) → 1
last2(‘xaxxaxaxx’) → 1
last2(‘axxxaaxx’) → 2
After a few minutes of thinking through it and checking out this answer on StackOverflow, I’ve come up with a solution!
But first, I wanted to share the long solution provided by CodingBat:
def last2(str): # Screen out too-short string case. if len(str) < 2: return 0 # last 2 chars, can be written as str[-2:] last2 = str[len(str)-2:] count = 0 # Check each substring length 2 starting at i for i in range(len(str)-2): sub = str[i:i+2] if sub == last2: count = count + 1 return count
Here is how you can put it into one line of code 🙂
def last2(str): return len([i for i in range(len(str) - 2) if str[i:i+2] == str[-2:]])
Can you think of an alternative way of solving this problem in one line of code?! If so, please share!