Ecom1414
Ecom1414

Reputation: 79

How to separate each line of a list python 2.7?

I am using python 2.7 and I have a list that consist of a price of a product and a link to that product. Each price and link is considered one item in the list. The problem is that the price is suppose to be at the end ONLY, and some of the items in the list have a price at the beginning and end. If the price is at the beginning the item starts with a '$' followed by the price and '\n'. When I print the list using '\n'.join(list) it separates the price at the beginning(which I want to remove) and the item itself on its on separate line, but I can't figure out how to delete the line that starts with '$' without deleting the whole item. right now i'm using this code:

myList = map(' '.join,zip(list1, list2))
das = '\n'.join(x3x) 
print das
#prints something like this:
$30                            #<--this line is part of the item in the 
iPhone 4 $30. eBay.com/iphone4 #list but I want to remove it because 
                               #it is repetitive and messes up what i'm
                               #trying to do.

What I normally use is:List = [v for v in myList if not v.startswith('$')] but this will remove the entire item if it starts with '$', not just the line with the '$30' in it.

Here is an example of the list right now:

['$34\n'iphone 4 $34 forsale.com/iphone4s, new car $20000 forsale.com/newcar]
#lets just say it is 2 items in the list, the first item has the price before
# and after the product, but the second item doesn't. I want to remove the '$34' 
# from the first item, but dont know how without deleting the entire 1st item.

so first item is price, product, price, and then link. Sometimes the price will be before the product, and this messes up my code, so I want to remove each price that happens to be at the beginning of my item without removing the whole thing.

Upvotes: 2

Views: 92

Answers (2)

bhansa
bhansa

Reputation: 7504

Check whether the list item startswith $ if it does, split the list item and remove the first part.

lista = ['$34 iphone 4 $34 forsale.com/iphone4s', 'new car $20000 forsale.com/newcar']

for i in range(len(lista)):

    if lista[i].startswith("$"):

        lista[i] = " ".join(lista[i].split(" ")[1:])

print lista  

Output:

['iphone 4 $34 forsale.com/iphone4s', 'new car $20000 forsale.com/newcar']

Upvotes: 2

P.Diddy
P.Diddy

Reputation: 46

You can insert a small check instead of immediately printing das. Something like

if das.find(" ") == -1:
    pass # don't print das and go to next line

Here I checked if there are no spaces in the string for example.

Upvotes: 0

Related Questions