[英]Remove leading and trailing spaces from a Python list
I have a list being produced from a webpage using json.loads. 我有一个使用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. 我知道如果我先将列表的每个元素转换为字符串,就可以使用
.strip()
来实现此.strip()
,但这对于字典而言不是有效的方法。 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
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: 但是,如果您想变得更健壮,则可以将
strip
函数应用于每个元素:
>>> 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.