How do I add a character to a string with Python? For example, I like to add a ":" to the middle of string: "0900" between 09 & 00.
3 Answers
You can use slicing.
time = "0900"
time_with_colon = time[:2] + ":" + time[2:]
print(time_with_colon)
09:00
You can't mutate a string, but you can slice it to get half of the string before an index and the half after the index. Then combine the two sides with the character you want in the middle.
Comments
_input = '0900'
input_to_list = list(_input)
input_to_list.insert(round(len(input_to_list)/2), ':')
_input_updated = "".join(input_to_list)
2 Comments
TypeError: integer argument expected, got float. (hint: dividing two numbers leaves a float value). The method is good though. Please correct it so that I can up-voteTo insert characters into a certain position you want to use something called slicing. You can have a look here to see the exact method: Add string in a certain position in Python
Assuming you always want to insert into the middle of a string of varying length then this would work as long as the sum of the characters is even (to be clear the sum of the characters you have provided is 4). Then the following would work fine:
string = "0099"
pos = int(len(string)/2)
new = string[:pos] + ":" + string[pos:]
print(new)
This won't work however if your string isn't of an even amount, when all the characters are added together, the : will go in the wrong place.
Sadly just using int() on a decimal value will not round it, it converts it to an integer by just copping off any floating value. As this example demonstrates:
>>> int(3.9)
3
instead you would want to use the round() function:
pos = round(len(string)/2)