4

I search a text file for the word Offering with a regular expression. I then use the start and end points from that search to look down the column and pull the integers. Some instances (column A) have leading white-space I do not want. I want to print just the number (as would be found in Column B) into a file, no leading white-space. Regex in a regex? Conditional?

price = re.search(r'(^|\s)off(er(ing)?)?', line, re.I)
if price:
    ps = price.start()
    pe = price.end()

             A             B
           Offering       Offer
            56.00         55.00 
            45.00         45.55
            65.222        32.00

3 Answers 3

9

You could use strip() to remove leading and trailing whitespaces:

In [1]: ' 56.00  '.strip()
Out[1]: '56.00'
Sign up to request clarification or add additional context in comments.

2 Comments

In the context of the regex result? I cannot .strip() the whole text file.
@CaptainCretaceous: You'll have to read it line by line (sorry, I thought that part was sufficiently obvious) and for each line do line[ps:pe].strip()
2

'^\s+|\s+$'

Use this to regular expression access leading and trailing whitespaces.

Comments

1

If you want to remove only the leading white spaces using regular expressions, you can use re.sub to do that.

>>> import re
>>>re.sub(r"^\s+" , "" , "  56.45")
'56.45'

Comments

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.