简体   繁体   中英

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.

Use the str.format() function.

So Try this:

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

Output:

2.5:6.5

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'

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())

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM