267

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"

0

9 Answers 9

438

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:]
'3558-79ACB6'
Sign up to request clarification or add additional context in comments.

4 Comments

Adding to this, you could use negative indices to get a position from the right, e.g. s[:-4]
Using the newer format string parlance: '{0}-{1}'.format(s[:4], s[4:])
Python strings are not immutable, but they don't support item assignment.
@micahbf The string build-in type is actually immutable according to the official docs: docs.python.org/3/library/stdtypes.html#text-sequence-type-str
87

This seems very easy:

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

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)

2 Comments

what is the time complexity of this?
@Embedded_Mugs I beleive it is O(n) because 1. substring selection is O(k)+O(n-k) = O(n) where k is the first part of the string (here k=4) 2. String concatenation is O(k+1) + O(n) = O(n). The string concatenation is O(n) because strings are mutable and it creates a new string for every concatenation.
41

As strings are immutable another way to do this would be to turn the string into a list, which can then be indexed and modified without any slicing trickery. However, to get the list back to a string you'd have to use .join() using an empty string.

>>> hash = '355879ACB6'
>>> hashlist = list(hash)
>>> hashlist.insert(4, '-')
>>> ''.join(hashlist)
'3558-79ACB6'

I am not sure how this compares as far as performance, but I do feel it's easier on the eyes than the other solutions. ;-)

Comments

19

Simple function to accomplish this:

def insert_str(string, str_to_insert, index):
    return string[:index] + str_to_insert + string[index:]

Comments

9

Python 3.6+ using f-string:

mys = '1362511338314'
f"{mys[:10]}_{mys[10:]}"

gives

'1362511338_314'

1 Comment

Works with negative indexes as well f"{mys[:-2]}_{mys[-2:]}" '13625113383_14'
7

I have made a very useful method to add a string in a certain position in Python:

def insertChar(mystring, position, chartoinsert ):
    mystring   =  mystring[:position] + chartoinsert + mystring[position:] 
    return mystring  

for example:

a = "Jorgesys was here!"

def insertChar(mystring, position, chartoinsert ):
    mystring   =  mystring[:position] + chartoinsert + mystring[position:] 
    return mystring   

#Inserting some characters with a defined position:    
print(insertChar(a,0, '-'))    
print(insertChar(a,9, '@'))    
print(insertChar(a,14, '%'))   

we will have as an output:

-Jorgesys was here!
Jorgesys @was here!
Jorgesys was h%ere!

3 Comments

Why do you calculate the length of the string tho?
Maybe he wanted to check the index was less than length of the string... and then forgot.
Python conventionally uses underscore case for function names, not camel case.
2

I think the above answers are fine, but I would explain that there are some unexpected-but-good side effects to them...

def insert(string_s, insert_s, pos_i=0):
    return string_s[:pos_i] + insert_s + string_s[pos_i:]

If the index pos_i is very small (too negative), the insert string gets prepended. If too long, the insert string gets appended. If pos_i is between -len(string_s) and +len(string_s) - 1, the insert string gets inserted into the correct place.

Comments

0

If you need to insert a given char at multiple locations, always consider creating a list of substrings and then use .join() instead of + for string concatenation. This is because, since Python str are mutable, + string concatenation always adds an aditional overhead. More info can be found here.

Comments

-1

I'd like to add another simple one-liner-solution ;)

'-'.join([_string[:4], _string[4:]]

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.