
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python program to change character of a string using given index
Suppose we have a string s, an index i and a character c. We have to replace the ith character of s using c. Now in Python, strings are immutable in nature. We cannot write a statement like s[i] = c, it will raise an error [TypeError: 'str' object does not support item assignment]
So, if the input is like s = "python", i = 3, c = 'P', then the output will be "pytPon"
To solve this, we will follow these steps −
left := s[from index 0 to i]
right := s[from index i+1 to end]
return left concatenate c concatenate right
Example
Let us see the following implementation to get better understanding
def solve(s, i, c): left = s[:i] right = s[i+1:] return left + c + right s = "python" i = 3 c = 'P' print(solve(s, i, c))
Input
python, 3, 'P'
Output
pytPon
- Related Articles
- Program to find the index of first Recurring Character in the given string in Python
- C# program to replace n-th character from a given index in a string
- Python Program to Get a Character From the Given String
- Python Program to Remove the nth Index Character from a Non-Empty String
- Find the index of the first unique character in a given string using C++
- C# Program to change a character from a string
- Python program to find occurrence to each character in given string
- Java Program to Get a Character From the Given String
- Python program to get characters from the string using the index
- Java program to find the Frequency of a character in a given String
- Java Program to replace all occurrences of a given character in a string
- How to delete a character from a string using python?
- Python program to count number of vowels using set in a given string
- Java Program to get a character located at the String's specified index
- Search index of a character in a string in Java

Advertisements