How to insert new characters into a string using Python ?

Published: June 19, 2023

Updated: June 19, 2023

DMCA.com Protection Status

There are several ways to add new characters to a string in Python:

Slicing a string to insert new characters

The first method for inserting characters into a string is slicing. This involves taking a substring from the original string and replacing it with a new one. For example, if you have the following string:

s = '20190807'

To separate the year, month, and day, we would like to use underscores (_):

year = s[0:4]
month = s[4:6]  
day = s[6:8]

Then using a python string literals:

new_s = f'{year}_{month}_{day}'

print( new_s )

returns

2019_08_07

Another example involves converting a string into integers for the year, month, and day. After that, a new string is created using a format:

year = int( s[0:4] )
month = int( s[4:6] )  
day = int( s[6:8] )

new_s = '{:04}_{:02}_{:02}'.format(year,month,day)

print( new_s )

also returns

2019_08_07

Using a list and join()

An alternative way to add new characters to a list is by converting a string into a list using the insert() method, and then using the join() method to convert the list back into a string.

s = '20190807'

l = [i for i in s]

l.insert(4,'_') 
l.insert(7,'_')

''.join(l)

gives

2019_08_07

Using regular expression

import re

s = 'd20190807_start1834_end1856'

m = re.search('d(.*)_start(.*)_end(.*)', s)

new_s = f'{m.group(1)}_{m.group(2)}_{m.group(3)}'

print( new_s )

returns

'20190807_1834_1856'

Replacing a specific word in a string

s = "Hello, how are you ?"

You can replace “hello” with “hi” like this:

 new_s = s.replace("Hello", "Hi")

 print(new_s)

This will result in the string 'Hi, how are you ?'. Note that you need to use both the string method replace() and specify the two strings as arguments for it to work properly.

Concatenate two or multiple strings

Concatenation is the process of combining two strings together. To use this method, use the plus (+) operator to add the two strings together, like so:

s1 = "Hello"

s2 = ", how are you ?"

s3 = s1 + s2

print(s3)

This will result in the new string,

Hello, how are you ?

Note that you need to use quotes around any text strings.

References

Links Site
Fancier Output Formatting docs.python.org
replace docs.python.org