Skip to content Skip to sidebar Skip to footer

How To Delete A String In A Loop With Python?

I have got a text like in this format: 'TEXT1';' TEXT2';'TEXT3';'TEXT4';'TEXT5 ';'';'TEXT6' 'TEXT7';' TEXT8';'TEXT9';'TEXT10';'TEXT11';'';'TEXT12' I used web-scraping and I want t

Solution 1:

If you want to remove empty string then you can simply use this,

newlist = filter(None, oldlist)

Solution 2:

a=["a","b","","d"]
i=0while i<len(a):
    if(a[i]==""):
        del a[i]
        i-=1
    i+=1

Solution 3:

Instead of deleting the empty string, you could just not append it.

The code could look like this:

datatable = []
for record in table.find_all('tr', class_="mytable"):
    temp_data = []
    fordatain record.find_all("td"):
        ifdata.text != "":     #Check if the datais an empty string or not
            temp_data.append(data.text.encode('latin-1'))   #Append the dataif it is not an empty string
    datatable.append(temp_data)
#print(datatable)
#[["TEXT1"," TEXT2","TEXT3","TEXT4","TEXT5 ","TEXT6"],["TEXT7"," TEXT8","TEXT9","TEXT10","TEXT11","TEXT12"]]

This works well, but if you still want to delete the empty string after adding it to the list then you can do that as follows:

datatable = []
for record in table.find_all('tr', class_="mytable"):
temp_data = []
for data in record.find_all("td"):
    temp_data.append(data.text.encode('latin-1'))
datatable.append(temp_data)
#print(datatable)
#[["TEXT1"," TEXT2","TEXT3","TEXT4","TEXT5 ","","TEXT6"],["TEXT7"," TEXT8","TEXT9","TEXT10","TEXT11","","TEXT12"]]

#Now remove the empty strings from datatable
for i inrange(len(datatable)):
    datatable[i] =filter(None, datatable[i])
    #Since filterreturns a filter object (iterator) in Python 3x, use
    #datatable[i] = list(filter(None, datatable[i]))
    #toconvert it to list in Python 3x
#print(datatable)
#[["TEXT1"," TEXT2","TEXT3","TEXT4","TEXT5 ","TEXT6"],["TEXT7"," TEXT8","TEXT9","TEXT10","TEXT11","TEXT12"]]

Post a Comment for "How To Delete A String In A Loop With Python?"