Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a string in a certain position?

Tags:

python

string

People also ask

How do you insert a character in a string at a certain position?

One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer. Syntax: str.

How do you add a string to a specific position in Python?

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.


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'

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)

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. ;-)


Simple function to accomplish this:

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

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

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

for example:

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 as an output:

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

Python 3.6+ using f-string:

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

gives

'1362511338_314'