-2

I have tried below code to split but I am unable to split

import re
s = "abcd[00451.00]"

print str(s).strip('[]')

I need output as only number or decimal format 00451.00 this value but I am able to get output as abcd[00451.00

  • possible duplicate of [Python strings split with multiple separators](http://stackoverflow.com/questions/1059559/python-strings-split-with-multiple-separators) – Jasper May 05 '14 at 13:14
  • 1
    @All who are answering this question. When I see a post like this one, I assume that the OP is beginner, so Please avoid one line solutions or please also provide details to the OP about your cool one liners. – ρss May 05 '14 at 13:14

3 Answers3

2

If you know for sure that there will be one opening and closing brackets you can do

s = "abcd[00451.00]"
print s[s.index("[") + 1:s.rindex("]")]
# 00451.00

str.index is used to get the first index of the element [ in the string, where as str.rindex is used to get the last index of the element in ]. Based on those indexes, the string is sliced.

If you want to convert that to a floating point number, then you can use float function, like this

print float(s[s.index("[") + 1:s.rindex("]")])
# 451.0
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 2
    Please add some explanation too, I don't think OP is very comfortable with your cool one liner. :) – ρss May 05 '14 at 13:13
0

You should use re.search:

import re
s = "abcd[00451.00]"

>>> print re.search(r'\[([^\]]+)\]', s).group(1)
00451.00
sshashank124
  • 31,495
  • 9
  • 67
  • 76
0

You can first split on the '[' and then strip the resulting list of any ']' chars:

[p.strip(']') for p in s.split('[')]
Kevin Thibedeau
  • 3,299
  • 15
  • 26