There should be a simple "pythonic" resolve for my issue.
I got a BeautifulSoup from where I'm extracting the text from elements with class
<ul>
<li class="category">
<i class="fa icon-cat"></i>
<a href="#">Red</a>
</li>
<li class="category">
<i class="fa icon-cat"></i>
<a href="#">Black</a>
</li>
<li class="category">
<i class="fa icon-cat"></i>
<a href="#">Blue</a>
</li>
</ul>
Using find_all, I'm extracting the text, then I join the values with a comma, then I print. What I'm trying to do is to replace the values (the colors) with different values.
categories = soup.find_all('li',{'class':'category'})
for i in range(len(categories)):
if categories[i] == 'Red':
categories[i] = '1'
if categories[i] == 'Black':
categories[i] = '2'
if categories[i] == 'Blue':
categories[i] = '3'
output = ','.join([i.text for i in categories])
print(output)
The result is:
Red,Black,Blue
So what I get are the initial values, no replacements, and I can't figure out why. I feel there's something very simple I'm missing and it drives me nuts!
======== SOLUTION
Based on @fazlul's answer below, I've modified a bit to make it more modular. The solution would be:
categories = [t.get_text(strip=True) for t in soup.find_all('li',{'class':'category'})]
for i in range(len(categories)):
if categories[i] == 'Red':
categories[i] = '1'
if categories[i] == 'Black':
categories[i] = '2'
if categories[i] == 'Blue':
categories[i] = '3'
output = ','.join([i for i in categories])
print(output)
Result is:
1,2,3