Maison  >  Article  >  développement back-end  >  Comment modifier une chaîne sur place en Python ?

Comment modifier une chaîne sur place en Python ?

WBOY
WBOYavant
2023-08-20 18:53:161386parcourir

Comment modifier une chaîne sur place en Python ?

Malheureusement, vous ne pouvez pas modifier les chaînes sur place car les chaînes sont immuables. Créez simplement une nouvelle chaîne à partir des quelques pièces que vous souhaitez collecter. Cependant, si vous avez toujours besoin d'un objet capable de modifier les données Unicode sur place, vous devez utiliser

  • Objet io.StringIO
  • Module tableau

Voyons ce dont nous avons discuté ci-dessus −

Renvoie une chaîne contenant tout le contenu du tampon

La traduction chinoise de

Exemple

est :

Exemple

Dans cet exemple, nous renverrons une chaîne avec tout le contenu du tampon. Nous avons un flux de texte 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())

Sortie

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

Maintenant, changeons la position du flux, écrivons du nouveau contenu et affichons

Changez la position du flux et écrivez une nouvelle chaîne

La traduction chinoise de

Exemple

est :

Exemple

Nous verrons un autre exemple et modifierons la position du flux à l'aide de la méthode seek(). Une nouvelle chaîne sera écrite à la même position à l'aide de la méthode write() −

.
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())

Sortie

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

Créez un tableau et convertissez-le en chaîne Unicode

La traduction chinoise de

Exemple

est :

Exemple

Dans cet exemple, créez un tableau en utilisant array() puis convertissez-le en chaîne Unicode en utilisant la méthode tounicode() -

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())

Sortie

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer