Python - Modify Strings



In Python, a string (object of str class) is of immutable type. An immutable object is the one which can be modified in place, one created in the memory. Hence, unlike a list, any character in the sequence cannot be overwritten, nor can we insert or append characters to it unless we use certain string method that returns a new string object.

However, we can use one of the following tricks as a workaround to modify a string.

Converting a String to a List

Since both string and list objects are sequences, they are interconvertible. Hence, if we cast a string object to a list, modify the list either by insert(), append(), or remove() methods and convert the list back to a string, to get back the modified version.

Example

We have a string variable s1 with WORD as its value. With list() built-in function, let us convert it to a l1 list object, and insert a character L at index 3. The we use the join() method in str class to concatenate all the characters.

s1="WORD"
print ("original string:", s1)
l1=list(s1)

l1.insert(3,"L")

print (l1)

s1=''.join(l1)
print ("Modified string:", s1)

It will produce the following output

original string: WORD
['W', 'O', 'R', 'L', 'D']
Modified string: WORLD

Using the Array Module

To modify a string, construct an array object. Python standard library includes array module. We can have an array of Unicode type from a string variable.

Example

import array as ar
s1="WORD"
sar=ar.array('u', s1)

Items in the array have a zero based index. So, we can perform array operations such as append, insert, remove etc. Let us insert L before the character D

sar.insert(3,"L")

Now, with the help of tounicode() method, get back the modified string

Example

import array as ar

s1="WORD"
print ("original string:", s1)

sar=ar.array('u', s1)
sar.insert(3,"L")
s1=sar.tounicode()

print ("Modified string:", s1)

It will produce the following output

original string: WORD
Modified string: WORLD

Using the StringIO Class

Python's io module defines the classes to handle streams. The StringIO class represents a text stream using an in-memory text buffer. A StringIO object obtained from a string behaves like a File object. Hence we can perform read/write operations on it. The getvalue() method of StringIO class returns a string.

Let us use this principle in the following program to modify a string.

Example

import io

s1="WORD"
print ("original string:", s1)

sio=io.StringIO(s1)
sio.seek(3)
sio.write("LD")
s1=sio.getvalue()

print ("Modified string:", s1)

It will produce the following output

original string: WORD
Modified string: WORLD
Advertisements