rmp2150
rmp2150

Reputation: 797

Split string by hyphen

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

Answers (4)

m0dem
m0dem

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

Padraic Cunningham
Padraic Cunningham

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

MattDMo
MattDMo

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 ints back, not just numbers in string format.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

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']

Ideone demo

Upvotes: 0

Related Questions