Hi,
Again I'm a newbie, going through how to think like a computer scientist online tutorial. I have 2 questions in the next lesson that I can't seem to crack, in relation to sub strings.
Here's the questions and my working below:
This one I can remove letters but I can't seem to remove the sub string only. The answer should be mippi and I keep getting mpp.

def remove_all(sub, strng):
    new_word = ''
    for letters in strng:
        print letters
        if letters not in sub:
            new_word += letters
    print new_word
remove_all('iss', 'mississippi')

This next question is again with sub strings and counting how many sub strings in the string. I've tried 2 different ways and neither work.. Here they are:

import string
def c_sub(sub, strng, start=0):
    """
    >>> count ('an', 'banana')
    2
    """
    count = 0
    index = string.find(sub, strng)
    while index != -1:
        count += 1
        start = index + 1
    return count
print c_sub("an", "banana")

and 2nd working:

def c_sub(sub, strng, start=0):
    """
    >>> count ('an', 'banana')
    2
    """
    count = 0
    for l in strng:
        for s in sub:
            if l == s:
                count += 1
    return count
print c_sub("an", "banana")

Recommended Answers

All 5 Replies

In your first code you are removing all the letters that are in sub (all the 'i' and 's') from the string strng.

The challenging part of learning Python is to get to know all the great functions and modules.

Actually strings have a function called replace(old, new) that you could use ...

# replace all occurances of "iss" in "mississippi" 
# with an empty string ""
print "mississippi".replace("iss", "")  # result --> mippi

Strings also have a function count(sub) ...

# count all occurances of "iss" in "mississippi" 
print "mississippi".count("iss")  # result --> 2

Would that be cheating?
BTW, a great cheat sheet for Python25 is at:
http://rgruet.free.fr/PQR25/PQR2.5.html

Thanks vegaseat. Yeah I think the point is to probably to write the function out, so then I understand how these built-in functions work.. The cheat sheet is fantastic. Thankyou :)

Hi vegaseat, just a question with these built in string modules. For the count subs in strings question I posted before, if I just use the string function and call it for ('ana', 'banana') it appears to only count 1, instead of the 2 'ana' that's there. It has already counted the 'a' and moves on. How would I get it to read the 'a' again?
Here's my function:

import string
def count(sub, strng, start=0):
    sub_count = strng.count(sub)
    return sub_count
print count('ana', 'banana')

count() will return the number of non-overlapping instances. See this page:

http://docs.python.org/library/string.html

I wrote a function a while back to find all occurrences of x in a larger string. The idea is that you step along the string looking at snippets the size of the word you are trying to find. Here's the function:

def find_x_in_string(x,strng)
    index = 0
    end = len(x) - 1
    return_list = []
    while 1:
        try:
            my_str = strng[index:end]
            if my_str == x:
                return_list.append(my_str)
            index += 1
            end += 1
        except IndexError:
            break
    return return_list

So, if you called the function for 'ana' and 'banana'

the function would compare 'ana' with

'ban' (FALSE)
'ana' (TRUE)
'nan' (FALSE)
'ana' (TRUE)

Resulting in 2 trues. Kindof a stupid thing though with this function, returnlist is going to be . DUR.

Not super useful. In most cases you're going to be saying len(returnlist) for the value you really want. But you could rewrite the function to be better!

How would I get it to read the 'a' again?

You would use the string.find() function. It returns the location of the string if found, or -1 if not found, and can take a second, optional argument that is the starting position for the search. So you would add one to the starting position of the found sub-string, i.e if it is greater than -1, and search again.

def count(sub, strng):
     sub_count = 0
     found = strng.find(sub)
     while found > -1:
         sub_count += 1
         print "found is", found
         found = strng.find(sub, found+1)

     return sub_count

print count('ana', 'banana')
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.