Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python- insert a character into a string

Tags:

python

string

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.

like image 768
user1777900 Avatar asked Dec 01 '12 01:12

user1777900


People also ask

Can you insert a character into a string Python?

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.

Can you insert characters into a string?

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.

What does %% mean in Python?

The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand.

How do you add a special character to a string in Python?

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.


1 Answers

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'
like image 99
sberry Avatar answered Oct 07 '22 16:10

sberry