Search code examples
pythonstringpython-3.xstrip

I don't know how to strip the end of this line


I have to enter two numbers in a function, and it outputs a string of odd numbers between the two numbers that you enter. Everything seems to be working fine, but I can't figure out how to strip the end correctly.

# getOdds.py
# A function that receives two integers and returns a string of consecutive even numbers between the two integers.

# Define the getOdds() functions
def getOdds(p, q):
    """ returns a string of odd numbers between integers p & q """

    # Define odd number string
    x = p
    while x <= q:
        if x % 2 == 0:
            x += 1

     # Calculate & print string
        else:
            print(x, end = ", ")
            str(x).strip(", ")
            x += 2

I just want the last number to not have a ", " at the end of it (eg. 1, 2, 3 instead of 1, 2, 3, ).

Why won't strip() work in this case? And what should I do instead?


Solution

  • The only way to stop the , from showing up at the last element is to prevent end=", " from happening on the last print, there are a few ways of going about this, but the simplest in my mind is to get a sequence of all the things you want to print and do it in one go, the print function is great at this:

    >>> print(*range(5), sep=", ")
    0, 1, 2, 3, 4
    

    You can make your own function behave this way by putting it into a helper generator function, instead of print(x,end=", ") you would simply yield x:

    def getOdds_gen_helper(p, q):
        """ generates odd numbers between integers p & q """
    
        # Define odd number string
        x = p
        while x <= q:
            if x % 2 == 0:
                x += 1
    
         # Calculate & print string
            else:
                yield x #!!! yield the values
                str(x).strip(", ")
                x += 2
    

    Then your actual getOdds function would simply call the helper like the above print statement:

    def getOdds(p,q):  
        """ prints all of the odd numbers between integers p & q """
    
        print(*getOdds_gen_helper(p,q), sep=", ")
    

    Note that your original docstring actually says "returns .." but it in fact returns nothing, if you wanted to return this string instead of printing it that would be equally easy with the generator and the str.join method:

    def getOdds(p,q):  
        """ returns a string of odd numbers between integers p & q """
        return ", ".join(str(p) for p in getOdds_gen_helper(p, q))