Search code examples
python-3.xparsingspace

Removing spaces from list items after parsing


I can not remove spaces from list items after parsing. Here is the fully working code.

​from bs4 import BeautifulSoup
from selenium import webdriver
import pandas as pd
import xlwings as xw
driver = webdriver.PhantomJS()
driver.get("http://www.cbr.ru/hd_base/dv/?P1=4")
driver.find_element_by_id('UniDbQuery_FromDate').clear()
driver.find_element_by_id('UniDbQuery_FromDate').send_keys('11.12.2017')
driver.find_element_by_id('UniDbQuery_ToDate').clear()
driver.find_element_by_id('UniDbQuery_ToDate').send_keys('13.12.2017')
driver.find_element_by_id("UniDbQuery_searchbutton").click()
z=driver.page_source
driver.quit()
soup=BeautifulSoup(z)
x=[]
for tag in soup.tbody.findAll('td'):
    x.append(tag.text) 
y=x[1::2]
y
['381 970,85', '370 534,87', '374 626,19']

The following code does not remove spaces.

​for i in y:
    i=i.replace(' ', '')
​y
['381 970,85', '370 534,87', '374 626,19']

Another code also does not clear the spaces.

​y = [x.strip(' ') for x in y]
​y
['381 970,85', '370 534,87', '374 626,19']

Please help to solve this problem. But please do not give advice if you have not tried your code.

I think the problem is in the encoding. But this assumption, since I'm new to programming.


Solution

  • y = ['381 970,85', '370 534,87', '374 626,19']
    lst2 = [e.replace(' ', '') for e in y]
    print(lst2)
    

    Your second case is almost right. However, the .strip does not remove the spaces inside the string.

    In your first case, the string is assigned to i and then the result of replace is assigned to the i a bit later. Then it is thrown away. It does not get into the list.