How to Change Values in a String in Python
Last Updated :
30 Jan, 2025
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.
Python
s = "x = 5; y = x + 3;"
res = s.replace("x", "z")
print(res)
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.
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.
Python
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)
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.
Python
import re
s = "x = 5; y = x + 3;"
s = re.sub(r'\bx\b', 'z', s)
print(s)
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".
Similar Reads
How to Change a Single Value in a NumPy Array NumPy arrays are a fundamental data structure in Python, widely used for scientific computing and data analysis. They offer a powerful way to perform operations on large datasets efficiently. One common task when working with NumPy arrays is changing a single value within the array. This article wil
6 min read
How to Replace Values in a List in Python? Replacing values in a list in Python can be done by accessing specific indexes and using loops. In this article, we are going to see how to replace the value in a List using Python. We can replace values in the list in several ways. The simplest way to replace values in a list in Python is by using
2 min read
How to use String Formatters in Python In Python, we use string formatting to control how text is displayed. It allows us to insert values into strings and organize the output in a clear and readable way. In this article, weâll explore different methods of formatting strings in Python to make our code more structured and user-friendly.Us
3 min read
Convert string to a list in Python Our task is to Convert string to a list in Python. Whether we need to break a string into characters or words, there are multiple efficient methods to achieve this. In this article, we'll explore these conversion techniques with simple examples. The most common way to convert a string into a list is
2 min read
How to Index and Slice Strings in Python? In Python, indexing and slicing are techniques used to access specific characters or parts of a string. Indexing means referring to an element of an iterable by its position whereas slicing is a feature that enables accessing parts of the sequence.Table of ContentIndexing Strings in PythonAccessing
2 min read
How to Convert Bytes to String in Python ? We are given data in bytes format and our task is to convert it into a readable string. This is common when dealing with files, network responses, or binary data. For example, if the input is b'hello', the output will be 'hello'.This article covers different ways to convert bytes into strings in Pyt
2 min read