Python-Modify String

In Python, the string is referred to as an immutable type. An immutable object will be altered in a place and created in the memory. Read this article to learn more about Python-Modify String.

Modify String

Python consists of the built-in methods that will be used on strings. In Python, a string (object of str class) is of immutable type. An immutable object can be modified in place, and created in the memory.

How to Convert a String to a List?

Both the string and list objects are referred to as sequences and are interconvertible. Thus, if we have a string object to the list, then modify the list either by the insert(), append () or remove () methods and then convert the list back to the string and then get the modified version.

# Convert string to list
my_string = "skill vertex"
my_list = list(my_string)

# Output the result
print(my_list)

Output

['s', 'k', 'i', 'l', 'l', ' ', 'v', 'e', 'r', 't', 'e', 'x']

How to use the Array Module?

It would be best to create the array object to modify the string. Thus, the Python standard consists of the array module. There is an array of Unicode types from the string variable. Let us look into this example to learn to create the array object.

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

Items in the provided array have a zero-based index. So, it will do the array operations such as append, insert, remove, etc. Here, you can see that characters are added at the index 6.

sar_list.insert(6, 's')

Use the tounicode() method to get the modified string.

import array as ar

# Original string
original_string = "hello skillvertex"

# Create an array of Unicode characters from the string "hello skillvertex"
sar = ar.array('u', original_string)

# Convert the array to a list
sar_list = list(sar)

# Insert 's' after index 5
sar_list.insert(6, 's')

# Convert the list back to an array
modified_sar = ar.array('u', sar_list)

# Output the original string
print("Original String:", original_string)

# Output the modified Unicode array
print("Modified Unicode Array:", modified_sar)

Output

Original String: hello skillvertex
Modified Unicode Array: array('u', 'hello sskillvertex')

How to Use the StringIO Class

In Python, there’s a special tool called StringIO in the io module. Imagine it as a pretend file that exists only in the computer’s memory. We can use it to read and write text, just like we do with files.

import io

# Create a StringIO object with an initial string
string_buffer = io.StringIO("Hello, this is a StringIO example.")

# Perform read operations
read_content = string_buffer.read(10)  # Read the first 10 characters
print("Read Content:", read_content)

# Perform write operations
string_buffer.write(" Welcome!")  # Append " Welcome!" to the string

# Get the current content using getvalue()
current_content = string_buffer.getvalue()

# Output the current content
print("Current Content:", current_content)

# Close the StringIO object (not necessary in this case)

# Try reading after closing (will not work)
try:
    read_after_close = string_buffer.read(5)
except ValueError as e:
    read_after_close = f"Error: {e}"

# Output the result after trying to read after closing
print("Trying to Read After Closing:", read_after_close)

Output

Read Content: Hello, thi
Current Content: Hello, this is a StringIO example. Welcome!
Trying to Read After Closing: Error: I/O operation on closed file.

Conclusion

This article will allow the students to improve their skills and knowledge about the Python- Modify String. It has listed how to convert the string to a list, and how to use the array module.

Python-Modify String- FAQs

Q1.Can strings in Python be modified and replaced?

Ans. Python strings are immutable and thus, they can’t be altered after it is created.

Q2. What is float () in Python?

Ans. The float is referred to as the reusable code in the Python Programming language that will turn the value into floating point numbers.

Q3. How to remove a string in Python?

Ans. Using str. replace(),Using translate(),
Using recursion, Using Native Method,
Using slice + concatenation,Using str. join()
Using byte array, Using remove prefix()

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment