Home  >  Article  >  Backend Development  >  How to modify a string in-place in Python?

How to modify a string in-place in Python?

WBOY
WBOYforward
2023-08-20 18:53:161427browse

How to modify a string in-place in Python?

Unfortunately, you cannot modify the string in place because strings are immutable. Just create a new string from the few parts you want to collect. However, if you still need an object that can modify Unicode data in-place, you should use

  • io.StringIO object
  • Array module

Let’s see what we discussed above −

Return a string containing the entire contents of the buffer

The Chinese translation of

Example

is:

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's change the position of the stream, write new content and display

Change the stream position and write new String

The Chinese translation of

Example

is:

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

The Chinese translation of

Example

is:

Example

In this example, use array() to create an array, and then use the tounicode() method to convert it to a Unicode string -

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?

The above is the detailed content of How to modify a string in-place in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more