[Python] How to change a string
In this article, I will explain how to change a string value with Python. Talking about swapping or replacing, you can use “replace()” or “translate()” function, but what can we use when we want to change the characters in specific indexes? For example, suppose we have the string “abcdefg”, and what we can do if we want to change the 3rd character “c” into “Z”? Actually, there are no offered functions to do that, so we have to implement it by ourselves.
Table of Contents
How to change a specific character in a string
Below is the code to change a specific character in a string. This changes the 3rd character “c” into “Z”.
str = "abcdefg" str = str[:2] + "Z" + str[3:] print(str) # abZdefg
Here, the str[:2] means the substring from str(the start index of the string) to str and str[3:] means the substring from str to str(the end index of the string).
Why not just code ” str = ‘Z’ “
However, you might think that it is easier to just code ” str = ‘Z’ “. Yes, you can do that with C or some other languages, but we aren’t allowed to do this with Python. Therefore, we have to code like above although it is a little bit confusing.
str = "abcdefg" str = "Z" # This cause an error!
How to change specific characters in a string
Next, how to change specific characters in a string? We can take the same process here, and the code below changes the 3rd to 6th characters into “ZZZZ”.
str = "abcdefg" str = str[:2] + "ZZZZ" + str[6:] print(str) # abZZZZg
A function to change specific characters in a string
If you have to do this a lot in your code, it’s better to define a function to do that. And below is the example function to do that. This function takes 3 arguments: “originalStr” is the original string which you want to change; “phrase” is the phrase which you want to insert; “index” is the index where you want to insert the phrase from. Feel free to copy and paste this function if you find it helpful.
def changeString(originalStr,phrase,index): str = originalStr str = str[:index-1] + phrase + str[index-1+len(phrase):] return str
str = "abcdefg" print(changeString(str,"ZZ",3)) # abZZefg
- Use “str = str[:2] + ‘Z’ + str[3:]” to change a specific character
- Do not use “str = ‘Z’ “, this causes an error