简体   繁体   中英

How can I replace string in a list with python?

I want to change all these : '/' to this : ' / ' and looking for the value before the / and insert a space character. (So iv got this : '8/3' and i want this : ' 8 / 3 ') This is my code:

 datatable=[] stop = 0 for ctable in soup.find_all('table', "ctable" ): for record in ctable.find_all('tr'): temp_data = [] for data in record.find_all('td'): temp_data.append(data.text.encode('latin-1')) if '/' in data.text: record2 = str(record).replace('/', ' / ') final_format = ' {} '.format(record2) if 'modul' in data.text: stop = 1 break datatable.append(temp_data) if stop == 1: break if stop == 1: break output.writerows(datatable) 

How can i reach it?

the find_all function from bs4 is not returning strings but bs tags, you need to convert record to string in order to use the replace method.

useful_string = str(record).replace('/', ' / ')

is the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM