Add string in a certain position in Python


Is there any function in Python that I can use to insert a value in a certain position of a string?

Something like this:

"3655879ACB6" then in position 4 add "-" to become "3655-879ACB6"

4/9/2014 5:40:21 AM

Accepted Answer

No. Python Strings are immutable.

>>> s='355879ACB6'
>>> s[4:4] = '-'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

It is, however, possible to create a new string that has the inserted character:

>>> s[:4] + '-' + s[4:]
4/14/2016 2:27:02 PM

This seems very easy:

>>> hash = "355879ACB6"
>>> hash = hash[:4] + '-' + hash[4:]
>>> print hash

However if you like something like a function do as this:

def insert_dash(string, index):
    return string[:index] + '-' + string[index:]

print insert_dash("355879ACB6", 5)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow