Changing one character in a string
Here is a code snippet that demonstrates how to change a single character in a string in Python:
string = "Hello World"
string = list(string)
string[6] = ','
string = "".join(string)
print(string)
Watch a video course
Python - The Practical Guide
Output:
Hello, World
Explanation:
- The first line assigns the string "Hello World" to the variable "string".
- The second line converts the string to a list of characters
- The third line access the 7th character of the list which is 'W' and replace it with ','.
- The fourth line joins the elements of the list back into a string
- Finally, the last line prints the modified string "Hello, World"
Alternatively, you can also use string slicing to change a single character in a string in Python.
Output:
Hello, World
Explanation:
- The first line assigns the string "Hello World" to the variable "string"
- The second line replaces the 7th character "W" with ","
- Finally, the last line prints the modified string "Hello, World"