Regular Expression - Python - Remove Leading White

2019-07-20 05:03发布

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

标签: python regex
3条回答
相关推荐>>
2楼-- · 2019-07-20 05:17

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

In [1]: ' 56.00  '.strip()
Out[1]: '56.00'
查看更多
聊天终结者
3楼-- · 2019-07-20 05:24

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'
查看更多
Luminary・发光体
4楼-- · 2019-07-20 05:33

'^\s+|\s+$'

Use this to regular expression access leading and trailing whitespaces.

查看更多
登录 后发表回答