Python Modify Strings
In the python, strings are immutable. This means that once a string is created, we cannot change it. We can only create a new string. But we can modify the existing string by reassigning a variable to another string. The new string can be a substring of the original string or a concatenation of two or more strings. Let’s look at some examples.
Example 1: Modify a String
Section titled “Example 1: Modify a String”# define a string
string = "Hello World"
string = string[:6] + "Python"
print(string)Output:
C:\Users\Your Name> python strings.py
Hello PythonIn the above example, we have modified the string by assigning a new string to the variable string. The new string is a concatenation of the first six characters of the original string and the string "Python".
flowchart LR
A["s = 'hello'"] --> B["s.upper()"]
B --> C["a NEW string 'HELLO'"]
C --> D{"did you assign it?"}
D -->|"s = s.upper()"| E["s is now 'HELLO'"]
D -->|"s.upper()"| F["the result is discarded; s is still 'hello'"]
A --> G["s[0] = 'H'"]
G --> H["TypeError: 'str' object does not support item assignment"]
H --> I["build a new one instead: 'H' + s[1:]"]
Convert String to List
Section titled “Convert String to List”In Python, a string can’t be updated but we can convert a string to a list and modify the list. After making the required changes, we can convert the list back to a string. We can use the list() function to convert a string to a list, and the str() function to convert a list back to a string.
# define a string
string = "Hello World"
# convert the string to a list
string = list(string)
# change the 7th character of the list
string[6] = 'P'
# convert the list back to a string
string = ''.join(string)
print(string)Output:
C:\Users\Your Name> python strings.py
Hello PorldIn the above example, we have converted the string to a list, changed the 7th character of the list, and converted the list back to a string.
append() and insert() Methods
Section titled “append() and insert() Methods”We can also use the append() and insert() methods to modify strings in Python. The append() method adds a single character to the end of the string, and the insert() method adds a single character at the specified index.
# define a string
string = "Hello World"
# convert the string to a list
string = list(string)
# append the letter 'P' to the list
string.append('P')
# insert the letter 'y' at index 6
string.insert(6, 'y')
# convert the list back to a string
string = ''.join(string)
print(string)Output:
C:\Users\Your Name> python strings.py
Hello PyWorldIn the above example, we have converted the string to a list, appended the letter 'P' to the list, inserted the letter 'y' at index 6, and converted the list back to a string.
Delete a String
Section titled “Delete a String”We can delete a string by using the del keyword. The del keyword can delete a single character, a range of characters, or an entire string.
# define a string
string = "Hello World"
# delete the letter 'H'
del string[0]
print(string)
# delete the letters 'el' from index 1 to index 3
del string[1:4]
print(string)
# delete the entire string
del string
print(string)Output:
C:\Users\Your Name> python strings.py
ello World
eo World
Traceback (most recent call last):
File "strings.py", line 10, in <module>
print(string)
NameError: name 'string' is not definedIn the above example, we have deleted the letter 'H' from the string, deleted the letters 'el' from index 1 to index 3, and deleted the entire string.
Conclusion
Section titled “Conclusion”In this tutorial, we have learned how to modify strings in Python. We have also learned that strings are immutable in Python. This means that once a string is created, we cannot change it. We can only create a new string. We can modify the existing string by reassigning a variable to another string. The new string can be a substring of the original string or a concatenation of two or more strings. We can also convert a string to a list and modify the list. After making the required changes, we can convert the list back to a string. We can also use the append() and insert() methods to modify strings in Python. The append() method adds a single character to the end of the string, and the insert() method adds a single character at the specified index. We can delete a string by using the del keyword. The del keyword can delete a single character, a range of characters, or an entire string. For more tutorials on Python, check out our Python Central Hub.
Section titled “In this tutorial, we have learned how to modify strings in Python. We have also learned that strings are immutable in Python. This means that once a string is created, we cannot change it. We can only create a new string. We can modify the existing string by reassigning a variable to another string. The new string can be a substring of the original string or a concatenation of two or more strings. We can also convert a string to a list and modify the list. After making the required changes, we can convert the list back to a string. We can also use the append() and insert() methods to modify strings in Python. The append() method adds a single character to the end of the string, and the insert() method adds a single character at the specified index. We can delete a string by using the del keyword. The del keyword can delete a single character, a range of characters, or an entire string. For more tutorials on Python, check out our Python Central Hub.”Check yourself
Section titled “Check yourself”-
`s = 'hello'` then `s.upper()` on its own line. What is `s`?
The call builds a new string and returns it; nothing assigned it, so the result is discarded. No warning is given — the statement is perfectly valid Python that does nothing.
pch.quizShowAnswer
B — `'hello'` — The call builds a new string and returns it; nothing assigned it, so the result is discarded. No warning is given — the statement is perfectly valid Python that does nothing.
-
What does `s[0] = 'H'` do?
Strings are immutable, so there is no item assignment at all. Build a new string instead: `'H' + s[1:]`.
pch.quizShowAnswer
B — `TypeError: 'str' object does not support item assignment` — Strings are immutable, so there is no item assignment at all. Build a new string instead: `'H' + s[1:]`.
-
Which benefit follows directly from strings being immutable?
A hash must stay stable for the lifetime of a key. The same reasoning is why a `set` is unhashable and a `frozenset` is not.
pch.quizShowAnswer
B — They can be dictionary keys, because their hash never changes — A hash must stay stable for the lifetime of a key. The same reasoning is why a `set` is unhashable and a `frozenset` is not.
-
What is the recommended way to build a long string piece by piece?
`join` allocates once. `+=` is not always quadratic on CPython — it can resize in place — but that optimisation depends on the string having exactly one reference, so `join` is the version that does not depend on an implementation detail.
pch.quizShowAnswer
B — Collect the pieces in a list and `''.join()` once — `join` allocates once. `+=` is not always quadratic on CPython — it can resize in place — but that optimisation depends on the string having exactly one reference, so `join` is the version that does not depend on an implementation detail.
Try it: Modify String Exercises
Section titled “Try it: Modify String Exercises”Exercise 1 – Upper and Lower Case
Section titled “Exercise 1 – Upper and Lower Case”Exercise 2 – Replace Substring
Section titled “Exercise 2 – Replace Substring”Exercise 3 – Strip Whitespace
Section titled “Exercise 3 – Strip Whitespace”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading