user2866402
user2866402

Reputation: 41

Split a string with space and bracket

I have some coordinates in form of

coordinate = (2.50 6.50)

I want it should split like

2.50:6.50

I have used coordinate.split(" "). But don't know how to use it properly to get above line.

Upvotes: 1

Views: 211

Answers (4)

zeako
zeako

Reputation: 148

Well if it's actually a string you can just go with:

coordinate.strip("()").replace(' ', ':')

which will get the output you wanted.

you can read more about strings in the docs
http://docs.python.org/2/library/string.html

Upvotes: 0

sudip
sudip

Reputation: 166

Since coordinate is a string as:

coordinate = '(2.50 6.50)'

Apart from val's answer you can do this also:

print("{0}:{1}").format(*coordinate[1:-1:].split())

Upvotes: 0

val
val

Reputation: 8689

K DawG's answer is good if you have them directly as tuples.

If you have them as a string coord = '(2.50 6.50)', you can parse it like this:

'(2.50 6.50)'.strip("()").split(' ')

And then, using his formatting:

>>> coord = '(2.50 6.50)'
>>> '{}:{}'.format(*coord.strip("()").split(' '))
'2.50:6.50'

Upvotes: 1

Deelaka
Deelaka

Reputation: 13693

Use the str.format() function.

So Try this:

coordinate = (2.50, 6.50)
print "{}:{}".format(*coordinate)

Output:

2.5:6.5

Upvotes: 1

Related Questions