Add string at specific position in Python

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

Something like that:

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

+89
python string
Mar 10 '11 at 1:32
source share
6 answers

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 

However, you can create a new line with the character entered:

 >>> s[:4] + '-' + s[4:] '3558-79ACB6' 
+156
Mar 10 2018-11-11T00:
source share

This seems very simple:

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

However, if you like something like a function, follow these steps:

 def insert_dash(string, index): return string[:index] + '-' + string[index:] print insert_dash("355879ACB6", 5) 
+36
Mar 10 2018-11-11T00:
source share

Since the strings are immutable, another way to do this is to turn the string into a list, which can then be indexed and modified without any clipping. However, to return the list to a string, you will need to use .join() using an empty string.

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

I'm not sure how this compares to performance, but I feel it is easier on the eyes than other solutions .; -)

+17
Mar 10 2018-11-11T00:
source share

I made a very useful method for adding a string to a specific position in Python :

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

eg:

 a = "Jorgesys was here!" def insertChar(mystring, position, chartoinsert ): longi = len(mystring) 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 a way out:

 -Jorgesys was here! Jorgesys @was here! Jorgesys was h%ere! 
+2
Feb 04 '16 at 15:13
source share

A simple function to do this:

 def insert_str(string, str_to_insert, index): return string[:index] + str_to_insert + string[index:] 
+1
Mar 16 '17 at 10:26
source share

If you want many inserts

 from rope.base.codeanalyze import ChangeCollector c = ChangeCollector(code) c.add_change(5, 5, '<span style="background-color:#339999;">') c.add_change(10, 10, '</span>') rend_code = c.get_changed() 
0
May 31 '15 at 15:27
source share



All Articles