Python List to String Conversion

Question:

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?

Asked By: smada

||

Answers:

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

parcelID = values[0]

Instead of

parcelID = str(values)
Answered By: David Robinson

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
Answered By: Paul Seeb

Use the Following code to select single value from multiple value of list randomly and then convert this value to the string

location_list=["Pakistan","China","Rusia","UAE","USA","UK","Saudia Arab"]
loc=random.choice(location_list)
print(str(location_list[0])) 
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.