Four ways to modify strings in Python

  • 2021-01-25 07:43:50
  • OfStack

In Python, a string is an immutable type, that is, a 1-bit character of a string cannot be directly modified.

So changing the elements of a string requires creating a new string.

There are four common modification methods.

Method 1: Convert the string to a list, modify the value, and compose the new string using join


>>> s='abcdef'         # The original string 
>>> s1=list(s)         # Converts strings to lists 
>>> s1             
['a', 'b', 'c', 'd', 'e', 'f'] # A list of every 1 An element is 1 A character 
>>> s1[4]='E'          # The first in the list 5 Change the characters to E
>>> s1[5]='F'          # The first in the list 5 Change the characters to E
>>> s1
['a', 'b', 'c', 'd', 'E', 'F'] 
>>> s=''.join(s1)        # Reconcatenates all characters in the list into strings with an empty string 
>>> s
'abcdEF'            # A new string 

Method 2: Slice a string sequence


>>> s='Hello World' 
>>> s=s[:6] + 'Bital'     #s before 6 A string +'Bital'
>>> s
'Hello Bital'
>>> s=s[:3] + s[8:]      #s before 3 A string +s The first 8 The string after the bit 
>>> s
'Heltal'

Method 3: ES18en functions that use strings


>>> s='abcdef'
>>> s=s.replace('a','A')    # with A replace a
>>> s
'Abcdef'
>>> s=s.replace('bcd','123')  # with 123 replace bcd 
>>> s
'A123ef'

Method 4: Assign (or reassign) to a variable


>>> s='Hello World'
>>> s2=' 2017'       # Variable assignment 
>>> s=s+s2
>>> s
'Hello World 2017'
>>> s='Hello World'
>>> s='Hello World 2017'  # To assign a value 
>>> s
'Hello World 2017'

conclusion


Related articles: