Python Forum

Full Version: Print only nth line
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
FOR EXAMPLE THE FILE IS AS FOLLOWS:

[b]<td class="text-center">28,426</td>

<td class="text-center">240</td>

<td class="text-center">6,893,221</td>


Now say, I use the following code:

x=re.findall('<td\s+class\="text\-center">([0-9.,]+)</td>',x)

print(x)

which will print me all the above numerical values, but I only want to print the 2nd line what so ever the value in it maybe, how do I do it?

Thanks in advance
Index the list:

x = re.findall('<td\s+class\="text\-center">([0-9.,]+)</td>',x)
print(x[2])
Use a parser Cool for HTML and not regex.
from bs4 import BeautifulSoup

html = '''\
<td class="text-center">28,426</td>
<td class="text-center">240</td>
<td class="text-center">6,893,221</td>'''

soup = BeautifulSoup(html, 'lxml')
td_tag1 = soup.select('td:nth-child(2)') # Using CSS selector
td_tag2 = soup.find_all('td')
Use:
>>> td_tag1
[<td class="text-center">240</td>]
>>> td_tag1[0].text
'240'
>>> 
>>> td_tag2[1]
<td class="text-center">240</td>
>>> td_tag2[1].text
'240'