How to Change Values in a String in Python
The task of changing values in a string in Python involves modifying specific parts of the string based on certain conditions. Since strings in Python are immutable, any modification requires creating a new string with the desired changes. For example, if we have a string like "Hello, World!", we might want to change "Hello" to "Hi", resulting in "Hi, World!".
Using str.replace()
replace() is one of the most efficient way to modify specific parts of a string as it searches for a specified substring and replaces it with another substring. This method works well when we need to replace all occurrences of a particular value.
s = "x = 5; y = x + 3;"
res = s.replace("x", "z")
print(res)
Output
z = 5; y = z + 3;
Explanation: replace() searches for all occurrences of "x" in the string s and replaces them with "z". It returns a new string res with the modifications, leaving the original string unchanged.
Table of Content
Using Split()
split() can be used to break a string into a list of substrings which allows for easy manipulation. After splitting the string, we can replace specific parts or elements then join the list back into a modified string.
s = "x = 5; y = x + 3;"
# Split `s` into words
w = s.split()
res = " ".join([i if i != "x" else "z" for i in w])
print(res)
Output
z = 5; y = z + 3;
Explanation: list comprehension replaces "x" with "z", and the modified list is joined back into a string using join() .
Using regular expression
re module allows us to search for specific patterns and modify values in a string based on those patterns. This makes regex an efficient method for replacing values, especially when we need to target specific words or characters.
import re
s = "x = 5; y = x + 3;"
s = re.sub(r'\bx\b', 'z', s)
print(s)
Output
z = 5; y = z + 3;
Explanation: r'\bx\b' uses a raw string (r) to interpret backslashes literally and \b to define a word boundary, ensuring only the whole word "x" is matched and replaced. The re.sub() function takes three arguments the pattern r'\bx\b', the replacement string 'z' and the string s where the replacement occurs, ensuring precise replacement of "x" with "z".