I think this should be relatively simple, but I can't figure it out. I have a string that represents coordinates, +27.5916+086.5640
and I need to put a comma in between the longitude and latitude so I get +27.5916,+086.5640
.
I'm looking through the API but I can't seem to find something for this.
Oh and I have to use Python 2.7.3 since the program I writing for doesn't support Python 3.X.
Use concatenation to insert a character into a string at an index. To insert a character into a string at index i , split the string using the slicing syntax a_string[:i] and a_string[i:] . Between these two portions of the original string, use the concatenation operator + to insert the desired character.
1. Using String. Insert a character at the beginning of the String using the + operator. Insert a character at the end of the String using the + operator.
The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand.
To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.
If your coordinates are c
, then this would work. Note, however, this will not work for negative values. Do you have to deal with negatives as well?
",+".join(c.rsplit("+", 1))
For dealing with negatives as well.
import re
parts = re.split("([\+\-])", c)
parts.insert(3, ',')
print "".join(parts[1:])
OUTPUT
+27.5916,+086.5640'
And for negatives:
>>> c = "+27.5916-086.5640"
>>> parts = re.split("([\+\-])", c)
>>> parts.insert(3, ',')
>>> "".join(parts[1:])
'+27.5916,-086.5640'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With