I have a text file that contains multiple records. Within the records, I am able to locate the line containing the desired text and read it into a string. Inside the line, I know the number of the starting character for the words I need. The length of the substring is not constant, however. How can I isolate the desired characters and move them into a variable? In this case, the desired information is written in all caps and is my test for locating the target phrase.

I am a newbie to python and am finding it difficult to convert to an object-oriented language.

Recommended Answers

All 5 Replies

Can you give us an example of your text and what you want to find/extract?

<b>(words only):</b><font color= "#0000FF"> BABY MILESTONES</font><br /><br />
The above is a line from an HTML source file. The target text is BABY MILESTONES

Loren41

You can use the 'index' method

>>> line = '<b>(words only):</b><font color= "#0000FF"> BABY MILESTONES</font><br /><br />'
>>> line.index("B")
44
>>> line.index("<", 44)  # 44 is the number of chars before BABY MILESTONES
59
>>> line[44:59]
'BABY MILESTONES'

Thanks Gribouillis. Now I have to figure out how to test for an uppercase letter. I won't always know it will be a "B."

As always, the solution seems simple after you see it!

Thanks Gribouillis. Now I have to figure out how to test for an uppercase letter. I won't always know it will be a "B."

As always, the solution seems simple after you see it!

You can use one of Python's string functions:

c = 'T'
print(c.isupper())  # --> True
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.