Skip to content

Changing one character in a string

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
string = "Hello World"
string = list(string)
string[5] = ','
string = "".join(string)
print(string)

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

Output:

output

console
Hello,World

Explanation:

  1. The first line assigns the string "Hello World" to the variable "string".
  2. The second line converts the string to a list of characters.
  3. The third line accesses the 6th character of the list (the space) and replaces it with ','.
  4. The fourth line joins the elements of the list back into a string.
  5. 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
string = "Hello World"
string = string[:5] + "," + string[6:]
print(string)

Output:

output

console
Hello,World

Explanation:

  1. The first line assigns the string "Hello World" to the variable "string".
  2. The second line replaces the space at index 5 with ','.
  3. Finally, the last line prints the modified string "Hello,World".

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.