Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to change character of a string using given index
Strings in Python are immutable, meaning you cannot modify individual characters directly. When you need to change a character at a specific index, you must create a new string using slicing and concatenation.
For example, if we have s = "python", i = 3, and c = 'P', attempting s[i] = c will raise a TypeError: 'str' object does not support item assignment.
Algorithm
To replace a character at index i with character c ?
Extract the left part:
s[0:i]Extract the right part:
s[i+1:]Concatenate:
left + c + right
Using String Slicing
The most common approach uses Python's slice notation ?
def change_character(s, i, c):
left = s[:i]
right = s[i+1:]
return left + c + right
# Example usage
s = "python"
i = 3
c = 'P'
result = change_character(s, i, c)
print(f"Original: {s}")
print(f"Modified: {result}")
Original: python Modified: pytPon
Using List Conversion
Convert string to list, modify, then join back ?
def change_character_list(s, i, c):
char_list = list(s)
char_list[i] = c
return ''.join(char_list)
# Example usage
s = "python"
i = 3
c = 'P'
result = change_character_list(s, i, c)
print(f"Original: {s}")
print(f"Modified: {result}")
Original: python Modified: pytPon
Multiple Character Changes
To change multiple characters at different positions ?
def change_multiple_characters(s, changes):
char_list = list(s)
for index, char in changes.items():
if 0 <= index < len(char_list):
char_list[index] = char
return ''.join(char_list)
# Example usage
s = "python"
changes = {1: 'Y', 3: 'P', 5: 'N'}
result = change_multiple_characters(s, changes)
print(f"Original: {s}")
print(f"Modified: {result}")
Original: python Modified: pYtPoN
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| String Slicing | O(n) | Single character change |
| List Conversion | O(n) | Multiple character changes |
Conclusion
Use string slicing for single character replacement and list conversion for multiple changes. Both methods create new string objects due to Python's string immutability.
