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:
Python - Replace Different Characters in String at Once
Next article icon

Replace a String character at given index in Python

Last Updated : 16 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, strings are immutable, meaning they cannot be directly modified. We need to create a new string using various methods to replace a character at a specific index.

Using slicing

Slicing is one of the most efficient ways to replace a character at a specific index.

Python
s = "hello"  idx = 1 replacement = "a" res = s[:idx] + replacement + s[idx+1:] print(res) 

Output
hallo 

Explanation:

  • The string is split into two parts: everything before the target index (text[:index]) and everything after (text[index+1:]).
  • The replacement character is inserted between these slices.
  • This method is simple, efficient, and works well for small or large strings.

Using list conversion

Converting the string to a list allows us to modify its characters directly before converting it back.

Python
s = "hello"  idx = 1 replacement = "a"  a = list(s) a[idx] = replacement  res = ''.join(b) print(res) 

Output
hallo 

Explanation:

  • The string is converted to a list because lists are mutable.
  • We modify the character at the target index and then rejoin the list into a string.
  • This method is slightly less efficient but useful for multiple modifications.

Using regular expressions

Regular expressions can be used to replace a character at a specific position by matching patterns.

Python
import re  s = "hello"  idx = 1 replacement = "a"  # Create a pattern to match the character at the specific index pattern = f"^(.{{{idx}}})."  res = re.sub(pattern, rf"\1{replacement}", s) print(res) 

Output
hallo 

Explanation:

  • The pattern matches the character at the desired index using lookbehind.
  • The re.sub() method replaces the matched character with the specified replacement.
  • This method is powerful but less efficient and more complex for simple replacements.

Using a manual loop

We can iterate through the string and build a new one, replacing the character at the given index.

Python
s = "hello" idx = 1 replacement = "a" res = ""  for i in range(len(s)):     if i == idx:         res += replacement     else:         res += s[i]  print(res) 

Output
hallo 

Explanation:

  • The loop iterates through the string and appends characters to a new string.
  • At the target index, the replacement character is added instead.

Related Articles:

  • Python String
  • String Slicing in Python
  • Regex Tutorial
  • Loops in Python


Next Article
Python - Replace Different Characters in String at Once
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - Replace Different Characters in String at Once
    The task is to replace multiple different characters in a string simultaneously based on a given mapping. For example, given the string: s = "hello world" and replacements = {'h': 'H', 'o': '0', 'd': 'D'} after replacing the specified characters, the result will be: "Hell0 w0rlD" Using str.translate
    3 min read
  • Remove Character in a String at a Specific Index in Python
    Removing a character from a string at a specific index is a common task when working with strings and because strings in Python are immutable we need to create a new string without the character at the specified index. String slicing is the simplest and most efficient way to remove a character at a
    2 min read
  • Find position of a character in given string - Python
    Given a string and a character, our task is to find the first position of the occurrence of the character in the string using Python. For example, consider a string s = "Geeks" and character k = 'e', in the string s, the first occurrence of the character 'e' is at index1. Let's look at various metho
    2 min read
  • Python - Replace all numbers by K in given String
    We need to write a python program to replace all numeric digits (0-9) in a given string with the character 'K', while keeping all non-numeric characters unchanged. For example we are given a string s="hello123world456" we need to replace all numbers by K in the given string so the string becomes "he
    2 min read
  • Python - Replace multiple characters at once
    Replacing multiple characters in a string is a common task in Python Below, we explore methods to replace multiple characters at once, ranked from the most efficient to the least. Using translate() with maketrans() translate() method combined with maketrans() is the most efficient way to replace mul
    2 min read
  • Reverse Alternate Characters in a String - Python
    We have to reverse the alternate characters in a given string. The task is to identify every second character in the string, reverse their order and keep the other characters unchanged. For example, "abcd" needs to be changed to "cbad" and "abcde" needs to be changed to "ebcda" This can be accomplis
    4 min read
  • Remove Multiple Characters from a String in Python
    Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Let’s explore the different ways to achieve this in det
    3 min read
  • Python | Remove given character from Strings list
    Sometimes, while working with Python list, we can have a problem in which we need to remove a particular character from each string from list. This kind of application can come in many domains. Let's discuss certain ways to solve this problem. Method #1 : Using replace() + enumerate() + loop This is
    8 min read
  • Python - Insert characters at start and end of a string
    In Python programming, a String is an immutable datatype. But sometimes there may come a situation where we may need to manipulate a string, say add a character to a string. Let’s start with a simple example to insert characters at the start and end of a String in Python. [GFGTABS] Python s = "
    2 min read
  • Python - Replace vowels in a string with a specific character K
    The task is to replace all the vowels (a, e, i, o, u) in a given string with the character 'K'. A vowel can be in uppercase or lowercase, so it's essential to account for both cases when replacing characters. Using str.replace() in a LoopUsing str.replace() in a loop allows us to iteratively replace
    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