Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Change a Single Value in a NumPy Array
Next article icon

How to Change Values in a String in Python

Last Updated : 30 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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) 

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()
  • Using string concatenation
  • Using regular expression

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) 

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.

Python
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".


Next Article
How to Change a Single Value in a NumPy Array

S

snikitasha19
Improve
Article Tags :
  • Python
  • python-string
  • python-basics
Practice Tags :
  • python

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 convert string to integer in Python?
    In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equiv
    3 min read
  • Change value in Excel using Python
    In this article, We are going to change the value in an Excel Spreadsheet using Python. Method 1: Using openxml: openpyxl is a Python library to read/write Excel xlsx/xlsm/xltx/xltm files. It was born from a lack of an existing library to read/write natively from Python the Office Open XML format. o
    2 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. U
    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 Content Indexing Strings in PythonAccessin
    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 Py
    2 min read
  • Convert String to Int in Python
    In Python, converting a string to an integer is important for performing mathematical operations, processing user input and efficiently handling data. This article will explore different ways to perform this conversion, including error handling and other method to validate input string during conver
    3 min read
  • Convert a String to Utf-8 in Python
    Unicode Transformation Format 8 (UTF-8) is a widely used character encoding that represents each character in a string using variable-length byte sequences. In Python, converting a string to UTF-8 is a common task, and there are several simple methods to achieve this. In this article, we will explor
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences