How to replace a character in a string with python

We will use replace method.

for example our string is “ABC”

We want to replace the C with D

x=”ABC”

x.replace(the character we want to replace, the character we want to place in the replacement)

so it will be x.replace(“C”, “D”)

The code


x="ABC"
x=x.replace("C","D")
print(x)


More string methods


x="Hello"

x=x.lower()
print(x)    #hello

x=x.upper()
print(x)    #HELLO

a = x.count('L')
print(a)    #2

b=x.index('O')
print(b)    #4

x=x.replace('L','l')
print(x)    #HEllO

#string is immutable.
x=x[:]+" world"
print(x)    #HEllO world

a=len(x)
print(a)  #4