Python 列表到字符串的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14568613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:50:36  来源:igfitidea点击:

Python List to String Conversion

pythonstringpython-2.xhttplib2

提问by smada

This seems like a simple task and I'm not sure if I've accomplished it already, or if I'm chasing my tail.

这似乎是一项简单的任务,我不确定我是否已经完成,或者我是否在追赶我的尾巴。

values = [value.replace('-','') for value in values] ## strips out hyphen (only 1)
            print values ## outputs ['0160840020']
            parcelID = str(values) ## convert to string
            print parcelID ##outputs ['0160840020']
            url = 'Detail.aspx?RE='+ parcelID ## outputs Detail.aspx?RE=['0160840020']

As you can see I'm trying to append the number attached to the end of the URL in order to change the page via a POST parameter. My question is how do I strip the [' prefix and '] suffix? I've already tried parcelID.strip("['") with no luck. Am I doing this correctly?

如您所见,我正在尝试将附加到 URL 末尾的数字附加到通过 POST 参数更改页面。我的问题是如何去除 [' 前缀和 '] 后缀?我已经尝试过 parcelID.strip("['") 没有运气。我这样做正确吗?

采纳答案by David Robinson

valuesis a list (of length 1), which is why it appears in brackets. If you want to get just the ID, do:

values是一个列表(长度为 1),这就是它出现在括号中的原因。如果您只想获取 ID,请执行以下操作:

parcelID = values[0]

Instead of

代替

parcelID = str(values)

回答by Paul Seeb

Assuming you actually have a list of values when you perform this (and not just one item) this would solve you problem (it would also work for one item as you have shown)

假设您在执行此操作时实际上有一个值列表(而不仅仅是一项),这将解决您的问题(它也适用于您所展示的一项)

values = [value.replace('-','') for value in values] ## strips out hyphen (only 1)

# create a list of urls from the parcelIDs
urls = ['Detail.aspx?RE='+ str(parcelID) for parcelID in values]

# use each url one at a time
for url in urls:
    # do whatever you need to do with each URL