Convert a number enclosed in parentheses (string) to a negative integer (or float) using Python?

前端 未结 7 2200
南方客
南方客 2021-02-19 21:52

In Python, what is the simplest way to convert a number enclosed in parentheses (string) to a negative integer (or float)?

For example, \'(4,301)\' to -4301, as commonly

7条回答
  •  南笙
    南笙 (楼主)
    2021-02-19 21:56

    This code could be a little bit longer, but straight forward and easy to maintain

    from pyparsing import Word, nums, OneOrMore
    
    integer = Word(nums)
    
    text = "blah blah (4,301) blah blah " 
    
    parser = OneOrMore(integer)
    
    iterator = parser.scanString( text )
    
    try:
        while True:
            part1 =  iterator.next()
            part2 =  iterator.next()
    except:
        x =  part1[0][0][0] + '.' +part2[0][0][0]
        print -float(x)
    

    Produces: -4.301

提交回复
热议问题