Draco Malfago
Draco Malfago

Reputation: 323

format strings in functions

I am exploring string formatting in functions, so lets say we have this simple and ugly function:

def my_string(z,a,b): 
    return '%d' '%s' '%s' % (z, a, b)

z = 1
x = ['monkey', 'monkey2', 'monkey3']
y = ['banana', 'banana2', 'banana3']

for item in x and y:
    print my_string(z, x, y)

I am expecting this to print:

1 monkey banana
1 monkey2 banana2
1 monkey3 banana3

But it is returning:

1['monkey', 'monkey2', 'monkey3']['banana', 'banana2', 'banana3']
1['monkey', 'monkey2', 'monkey3']['banana', 'banana2', 'banana3']

I cannot on earth understand why the return is as it is and not as I expect it to be, print x[0] will indeed print the first item of x which is monkey. Where am I thinking wrong?

Upvotes: 1

Views: 56

Answers (1)

Keiwan
Keiwan

Reputation: 8251

It doesn't work because with every loop you are printing x and y which are your lists and not the items inside the lists. Try this code:

def my_string(z,a,b): 
    return '%d ' '%s ' '%s' % (z, a, b)

z = 1
x = ['monkey', 'monkey2', 'monkey3']
y = ['banana', 'banana2', 'banana3']

for item1,item2 in zip(x, y):
    print my_string(z, item1, item2)

zip enables you to iterate over two lists at the same time by returning a tuple. See here for more information on this.

Upvotes: 1

Related Questions