0

I have a list being produced from a webpage using json.loads. I am displaying this with the following code:

myvar = json.loads(response.text)
print myvar[0],',',myvar[1],',',myvar[2]

This prints as:

0 , 1 , 2

What I would like it to print as is this:

0,1,2

I know I could achieve this by using .strip() if i converted each element of the list to a string first, but this is not a valid method for a dictionary. Is there a way to strip elements of a list without converting to a string first?

Thanks

EDIT:

At request of responder, here is the full code being used:

import requests

url = 'http://www.whoscored.com/stagestatfeed'
        params = {
            'against': '1', 
            'field': '1',
            'stageId': '9155',
            'teamId': '32',
            'type': '7'
            }
        headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36',
           'X-Requested-With': 'XMLHttpRequest',
           'Host': 'www.whoscored.com',
           'Referer': 'http://www.whoscored.com/Teams/32/Statistics/England-Manchester-United'}

        responser = requests.get(url, params=params, headers=headers)

        print '**********Shots Against (Action Zone) - Away:**********'
        print '-' * 170
        fixtures = json.loads(responser.text)
        print("%s,%s,%s" % (fixtures[0].strip(), fixtures[1].strip(), fixtures[2].strip()))
        print responser.text
        print '-' * 170
gdogg371
  • 3,879
  • 14
  • 63
  • 107
  • Would help to see what myvar is and what it contains. – Chris Arena Sep 14 '14 at 17:23
  • 2
    Since no answer is pointing this out so far: The reason you're getting spaces in between your values is that the [`print` statement](https://docs.python.org/2/reference/simple_stmts.html#print) with multiple arguments (`print a, b, c`) automatically inserts them for you: *"A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line.*" – Lukas Graf Sep 14 '14 at 17:40

1 Answers1

1

Looks like you just need this:

>>> myvar = [1, 2, '3']
>>> ",".join(map(str, myvar))
'1,2,3'

But, if you want to be more robust, then apply strip function to every element:

>>> myvar = [1, 2, '3']
>>> ",".join(map(lambda x: str(x).strip(), myvar))
'1,2,3'

>>> myvar = [1, 2, 3, ' 4 ']
>>> ",".join(map(lambda x: str(x).strip(), myvar))
'1,2,3,4'
stalk
  • 11,934
  • 4
  • 36
  • 58
  • hi, thanks for replying. that worked great. could you briefly explain to me though what the 'lambda' and 'x' do in the above though? thanks... – gdogg371 Sep 14 '14 at 17:47
  • `lambda` - it is a short function. [Here](http://stackoverflow.com/q/890128/821594) are some details. – stalk Sep 14 '14 at 18:00