- Python Replace Character in String by Index
- Method 1: Converting String to List
- Method 2: Using string slicing
- Speed Comparison of both the methods
- Conclusion
- Python: Replace character in string by index position
- Use Python string slicing to replace nth character in a string
- Frequently Asked:
- Python function to replace a character in a string by index position
- Python: Replace characters at multiple index positions in a string with the same character
- Python: Replace characters at multiple index positions in a string with different characters
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
- Python String – Replace character at Specific Position
- Python – Replace Character at Specific Index in String
- Examples
- 1. Replace character at a given index in a string using slicing
- 2. Replace character at a given index in a string using list
- Summary
Python Replace Character in String by Index
In this article, you are going to learn how to replace character in string by index in Python using 2 different methods. We will also look at the speed comparison of both methods.
Previously we have seen how to replace a character in a string in Python when the character is known. Here index of the character is used to replace the character in the string.
Method 1: Converting String to List
The string is immutable in Python. So, we can’t directly replace a character in a string. It will throw an error.
To overcome this, you can convert the string to list and then replace the character in the list at the given index.
Finally, convert the list to string using the join() method and assign it to the original string.
# Method 1 # replace character in string by index def replace_char(str, index, char): # convert string to list str = list(str) # assign character to index str[index] = char # join the list and return the string return ''.join(str) str = "Hello World" # replace character at index 0 with 'B' print(replace_char(str, 0, 'T')) # replace character at index 6 with 'B' print(replace_char(str, 6, 'B'))
Method 2: Using string slicing
Another way to replace a character in a string by the index is using string slicing.
String slicing is a technique to access a part of a string. It is done by specifying the start and end index of the substring. For example, str[0:5] will return the substring from index 0 to 5.
Using this we access the substring from index 0 to index-1 and concatenate it with the character and the substring from index+1 to the end of the string.
# Method 2: # using string slicing def replace_char(str, index, char): # concatenate the substring from 0 to index-1 and character # and substring from index+1 to the end of the string str = str[:index] + char + str[index+1:] # return the string return str str = "tutorials tonight" # replace character at index 0 with 'T' print(replace_char(str, 0, 'T')) # replace character at index 10 with 'T' print(replace_char(str, 10, 'T'))
Tutorials tonight tutorials Tonight
You can see in the above example, the character at index 0 is replaced with ‘T’ and the character at index 10 is replaced with ‘T’ using the string slicing method.
Speed Comparison of both the methods
Let’s compare the speed of both methods and see which one is faster.
For this, we will use the time module. It provides various time-related functions.
Here we will use time.time() function which returns the number of seconds passed since January 1, 1970, 00:00:00 (UTC) at Unix systems.
So, we will calculate the time difference between the start and end time of the function to get the time taken by the function to execute.
import time # Method 1: replace character in string by index def replace_char1(str, index, char): str = list(str) str[index] = char return ''.join(str) # method 2: using string slicing def replace_char2(str, index, char): str = str[:index] + char + str[index+1:] return str # compare the time taken by both methods def compare_time(): str = "Hello World" index = 5 char = 'z' t1 = time.time() for i in range(1000000): replace_char1(str, index, char) t2 = time.time() for i in range(1000000): replace_char2(str, index, char) t3 = time.time() print("Time taken by method 1: ", t2-t1) print("Time taken by method 2: ", t3-t2) compare_time()
('Time taken by method 1: ', 0.6108551025390625) ('Time taken by method 2: ', 0.2126619815826416)
As you can see, the time taken by method 2 is less than method 1. So, method 2 ⭐️ is faster than method 1.
Conclusion
In this article, you have learned two methods to replace a character in a string by index.
Also, we found that method 2 is faster than method 1. So, you can preferably use method 2 to replace a character in a string by an index.
Python: Replace character in string by index position
In this article, we will discuss how to replace a character in a string at a specific position. Then we will also see how to replace multiple characters in a string by index positions.
Table of Contents
Use Python string slicing to replace nth character in a string
To replace a character at index position n in a string, split the string into three sections: characters before nth character, the nth character, and the characters after the nth characters. Then join back the sliced pieces to create a new string but use instead of using the nth character, use the replacement character. For example,
sample_str = "This is a sample string" n = 3 replacement = 'C' # Replace character at nth index position sample_str = sample_str[0:n] + replacement + sample_str[n+1: ] print(sample_str)
In the above example, we replaced the character at index position 3 in the string. For that, we sliced the string into three pieces i.e.
Frequently Asked:
- Characters from index position 0 to 2.
- Character at index position 3
- Characters from index position 3 till the end of string.
Then we joined the above slices, but instead of using the character at position 3, we used the replacement character ‘C’.
Python function to replace a character in a string by index position
The slicing approach is good to replace the nth character in a string. But what if somebody tries to replace a character at an index that doesn’t exist? That means if the given index position for replacement is greater than the number of characters in a string, then it can give unexpected results. Therefore we should always check if the given nth position is in the range or not.
To avoid this kind of error, we have created a function,
def replace_char_at_index(org_str, index, replacement): ''' Replace character at index in string org_str with the given replacement character.''' new_str = org_str if index < len(org_str): new_str = org_str[0:index] + replacement + org_str[index + 1:] return new_str
Now let’s use this function to replace nth character in a string,
sample_str = "This is a sample string" # Replace character at 3rd index position sample_str = replace_char_at_index(sample_str, 3, 'C') print(sample_str)
Let’s try to replace a character at index position, which is out of bounds,
sample_str = "This is a sample string" # Replace character at 50th index position sample_str = replace_char_at_index(sample_str, 50, 'C') print(sample_str)
Python: Replace characters at multiple index positions in a string with the same character
We have few index positions in a list, and we want to replace all the characters at these index positions. To do that, we will iterate over all the index positions in the list. And for each index, replace the character at that index by slicing the string,
sample_str = "This is a sample string" # Index positions list_of_indexes = [1, 3, 5] # Replace characters at index positions in list for index in list_of_indexes: sample_str = replace_char_at_index(sample_str, index, 'C') print(sample_str)
Python: Replace characters at multiple index positions in a string with different characters
In the above example, we replace all the characters at given positions by the same replacement characters. But it might be possible that in some scenarios, we want to replace them with different replacement characters.
Suppose we have a dictionary that contains the index positions and the replacement characters as key-value pairs. We want to replace all the characters at these index positions by their corresponding replacement character. To do that, we will iterate over all the key-value pairs in the dictionary. And for each key, replace the character at that index position by the character in the value field. For example,
sample_str = "This is a sample string" char_to_replace = # Replace multiple characters with different replacement characters for index, replacement in char_to_replace.items(): sample_str = replace_char_at_index(sample_str, index, replacement) print(sample_str)
We can use the string slicing in python to replace the characters in a string by their index positions.
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Python String – Replace character at Specific Position
Python – Replace Character at Specific Index in String
To replace a character with a given character at a specified index, you can use python string slicing as shown below:
string = string[:position] + character + string[position+1:]
where character is the new character that has to be replaced with and position is the index at which we are replacing the character.
Examples
1. Replace character at a given index in a string using slicing
In the following example, we will take a string, and replace character at index=6 with e.
Python Program
string = 'pythonhxamples' position = 6 new_character = 'e' string = string[:position] + new_character + string[position+1:] print(string)
2. Replace character at a given index in a string using list
In the following example, we will take a string, and replace character at index=6 with e. To do this, we shall first convert the string to a list, then replace the item at given index with new character, and then join the list items to string.
Python Program
string = 'pythonhxamples' position = 6 new_character = 'e' temp = list(string) temp[position] = new_character string = "".join(temp) print(string)
Summary
In this tutorial of Python Examples, we learned how to replace a character at specific index in a string with a new character.