Changing one character in a string
Here is a code snippet that demonstrates how to change a single character in a string in Python:
Here is a code snippet that demonstrates how to change a single character in a string in Python:
Change a single character in a string in Python
python— editable, runs on the server
Info
Watch a video course: Python - The Practical Guide
Output:
output
Hello,WorldExplanation:
- 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 accesses the 6th character of the list (the space) and replaces 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".
Note: Python strings are immutable, meaning you cannot modify them in place. You must create a new string using conversion or slicing.
Alternatively, you can also use string slicing to change a single character in a string in Python.
Use string slicing to change a single character in a string
python— editable, runs on the server
Output:
output
Hello,WorldExplanation:
- The first line assigns the string "Hello World" to the variable "string".
- The second line replaces the space at index 5 with ','.
- Finally, the last line prints the modified string "Hello,World".