Reputation: 797
I have a strings in the format of feet'-inches" (i.e. 18'-6"
) and I want to split it so that the values of the feet and inches are separated.
I have tried:
re.split(r'\s|-', `18'-6`)
but it still returns 18'-6
.
Desired output: [18,6]
or similar
Thanks!
Upvotes: 0
Views: 6648
Reputation: 1008
The built-in split method can take an argument that will cause it to split at the specified point.
"18'-16\"".replace("'", "").replace("\"", "").split("-")
A one-liner. :)
Upvotes: -1
Reputation: 180441
Just split normally replacing the '
:
s="18'-6"
a, b = s.replace("'","").split("-")
print(a,b)
If you have both "
and '
one must be escaped so just split and slice up to the second last character:
s = "18'-6\""
a, b = s.split("-")
print(a[:-1], b[:-1])
18 6
Upvotes: 3
Reputation: 102892
A list comprehension will do the trick:
In [13]: [int(i[:-1]) for i in re.split(r'\s|-', "18'-6\"")]
Out[13]: [18, 6]
This assumes that your string is of the format feet(int)'-inches(int)"
, and you are trying to get the actual int
s back, not just numbers in string format.
Upvotes: 0
Reputation: 627022
You can use
import re
p = re.compile(ur'[-\'"]')
test_str = u"18'-6\""
print filter(None,re.split(p, test_str))
Output:
[u'18', u'6']
Upvotes: 0