0

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?

4
  • Strings are immutable. record.replace isn't doing anything, but your error seems to indicate that record is set to None Commented Jul 10, 2017 at 13:16
  • correct me if I'm wrong but even record.replaceworks you are not storing it anywhere or using it afterwards so the line basically does nothing to affect the outcome of the code. Maybe it is easier if you just get your data from the soup and then in a different loop correct it. Commented Jul 10, 2017 at 13:22
  • i edited my question, i have to use "data.text.replace" and it is working, but i want to reach this format: '8/3' -- > ' 8 / 3 ' Commented Jul 10, 2017 at 13:26
  • @tardos93 strings are immutable you have to do data2 - data.text.replace('/', ' / ') Commented Jul 10, 2017 at 13:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You also need to make sure to do record2 = str(record).replace('/', ' / ') cause strings are immutable so you need to put them into a new variable
done, thanks for the advice, if he wants to store the actual value, that is the way to go
it is working, thank you! But the second part of my question? I have this value '8/3' and i want this : ' 8 / 3 ' (i have to insert a space before the 8, because if i open it in csv i get a data format.)
this is not a very pretty way to do it, but if you can isolate the values like 8/3, you can use string format like: final_format = ' {} '.format(useful_string)
i updated my code, but it isnt working, i get the same bad result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.