-2
b = 'abbaab'
count = 0
width = 2
for k in range(0, len(b), width):
    print b[k:k + width]

gives me

 ab
 ba
 ab

but I need to use return instead of print. I don't know how to store each line into something, the things I tried said index out of range.

jdigan
  • 55
  • 2
  • 5

3 Answers3

1

I think this will work , Solution in Python 2.7.6:

def print_list(b):
    count = 0
    width = 2
    for k in range(0, len(b), width):
        yield b[k:k + width]
b = 'abbaab'
l = list(print_list(b))
for i in l:
    print i 

Output:

ab
ba
ab

Here I am using yield statement to instead of return to return the every line element and trying to convert all into list and every element in list represent each line Or else it is not necessary to convert it into list you can use this:

 for i in print_list(b):
    print i 

If you want to use return then Solution :

def print_list(b):
count = 0
width = 2
ans = []
for k in range(0, len(b), width):
    ans.append(b[k:k + width])
return ans

b = 'abbaab'
for i in print_list(b):
    print i

Hope this helps.

Kalpesh Dusane
  • 1,477
  • 3
  • 20
  • 27
0

print and return are very different.

Print is a function that will just print out something to the screen. return is a command that basically tells what value a function should return. For example:

def func1():
    print 1

def func2()
    return 2

if you do

first_result = func1()
second_result = func2()

you will see that

first_result = None
second_result = 2

but if you run them

func1()
func2()

you'll see that only 1 will be printed to the screen. In order to print the return of a function, you have to explictly ask for it

print func2()

With that in mind, and heading to your problem, you can store your things and return that to the function, and just then ask for python to print everything out

def func3():
    b = 'abbaab'
    count = 0
    width = 2
    things = []
    for k in range(0, len(b), width):
        things.append(b[k:k + width])
    return things

print func3()

Of course in this csae, you will print all values at once. In order to print each line separately, iterate the result and print each element

value_returned = func3()
for element in value_returned:
    print element
rafaelc
  • 57,686
  • 15
  • 58
  • 82
0

You want return to be same as print, return switches context from callee to caller function, with some value or none. Whereas print is used to send some output to console

They both cannot be same.

In your case, assuming that you want to write this code snippet as a function and return values that are being printed, it should be done as follows:

def foo():
    b = 'abbaab'
    stack = []
    count = 0
    width = 2
    for k in range(0, len(b), width):
        stack.append(b[k:k + width]);
    return stack;
Prateek Gupta
  • 538
  • 2
  • 10