Skip to content Skip to sidebar Skip to footer

Python 2.7 Print Vs Return

I'm trying to grab every other letter from a string but i'm having some problem with print and return. Why when i use print, the output is what i want and when i use return i only

Solution 1:

As everyone has pointed out, your function returns the instance on the first loop. You can use a temporary variable to store your result and return that result.

You can use the statement below inside a function:

return ''.join([ur_string[i] for i in range(0, len(ur_string), 2)])

Solution 2:

Maybe what you want is this:

def string_bits(the_str):
    x = len(the_str)
    for i in range(0,x,2):
        yield the_str[i]

or the_str[::2] takes only even position character


Solution 3:

function 1

Here, you loop over the whole string and print each letter. The loop finishes when there are no more letters, and the function exits.

def string_bits(str):
    x = len(str)
    for i in range(0,x,2):
        print str[i]

function 2

def string_bits(str):
    x = len(str)
    for i in range(0,x,2):
        return str[i]

Here, you loop over the whole string, but instead of printing str[i] you are returning it. The return causes your function to exit, and so the loop doesn't continue on to the other letters.

Hope this helps!


Solution 4:

This is because when you return, the program exits the function, whereas using print the program continues the loop.

As strings are iterable, you can use slicing to get the characters you want by specifying the step as 2:

To return a string:

def string_bits(s):
    return s[::2]

To return a list of characters:

def string_bits(s):    
    return list(s[::2])

Alternatively, you could use yield to create a generator:

def string_bits(s):
    for char in s[::2]:
        yield char

Post a Comment for "Python 2.7 Print Vs Return"