How do I modify a string in place in Python?


Unfortunately, you cannot modify a string in place because strings are immutable. Simply create a new string from the several parts you want to gather it from. Though, if you still need an object with the ability to modify in-place unicode data, you should for

  • The io.StringIO object
  • The Array module

Let’s see what we discussed above −

Return a string with the entire contents of the buffer

Example

In this example, we will return a string with the entire contents of the buffer. We have a text stream StringIO −

import io myStr = "Hello, How are you?" print("String = ",myStr) # StringIO is a text stream using an in-memory text buffer strIO = io.StringIO(myStr) # The getvalue() returns a string containing the entire contents of the buffer print(strIO.getvalue())

Output

String = Hello, How are you?
Hello, How are you?

Now, let us change the stream position, write new content and display

Change the stream position and write new String

Example

We will see another example and change the stream position using the seek() method. A new string will be written at the same position using the write() method −

import io myStr = "Hello, How are you?" # StringIO is a text stream using an in-memory text buffer strIO = io.StringIO(myStr) # The getvalue() returns a string containing the entire contents of the buffer print("String = ",strIO.getvalue()) # Change the stream position using seek() strIO.seek(7) # Write at the same position strIO.write("How's life?") # Returning the final string print("Final String = ",strIO.getvalue())

Output

String = Hello, How are you?
Final String = Hello, How's life??

Create an array and convert it to Unicode string

Example

In this example, create an array using array() and then convert it to the Unicode string using the tounicode() method −

import array # Create a String myStr = "Hello, How are you?" # Array arr = array.array('u',myStr) print(arr) # Modifying the array arr[0] = 'm' # Displaying the array print(arr) # convert an array to a unicode string using tounicode print(arr.tounicode())

Output

array('u', 'Hello, How are you?')
array('u', 'mello, How are you?')
mello, How are you?

Updated on: 16-Sep-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements