Python Forum

Full Version: Not quite getting the correct Output from a function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello.

I have a function that I'm trying to create.
When receiving a non-empty string input, I want to return a string containing every other character 2n+2 times.
(Where "n" is the 0-based index of the letter).

Example: input_string = "Rivers" #RRvvvvvvrrrrrrrrrr

def string_expansion( input_string ):
    n=0
    if len(input_string) == 0:
        return "invalid entry"
    #for n in range(len(input_string)):
    #    value = input_string[n::2]
    #    return value * (2*n+2)
    for n in range(0,len(input_string),2):
        #value = input_string[n]
        #strlen = len(input_string)
        print(value * (2*n+2))
    pass

input_string = "Rivers"
print(string_expansion(input_string))
I am getting:

Output:
RR vvvvvv rrrrrrrrrr None
I want to get:
Output:
RRvvvvvvrrrrrrrrrr
What am I goofing up here?
Your code is printing the value per loop and not returning anything.
You need a container for your string before the loop, add to it inside the loop and return it after the loop.
If function doesn't return anything explicitly with return statement then it returns None (you can see it in your output: three lines printed and then None). In case of empty string function returns 'invalid entry' therefore there will be no None.

I would go for oneliner:

>>> s = 'Rivers'
>>> ''.join(char*(2*(i-1)+2) for i, char in enumerate(s, start=1) if i % 2)
'RRvvvvvvrrrrrrrrrr'
Thank you for the replies. I tried both recommendations and they worked wonderfully...and I learned two different approaches in the process. Much appreciated!