python replace a character in a string code example

Example 1: python replace char in string

# Python3 program to demonstrate the  
# use of replace() method   
  
string = "geeks for geeks geeks geeks geeks" 
   
# Prints the string by replacing geeks by Geeks  
print(string.replace("geeks", "Geeks"))  
  
# Prints the string by replacing only 3 occurrence of Geeks   
print(string.replace("geeks", "GeeksforGeeks", 3))

Example 2: python change character in string

mytext = 'Hello Zorld'
mytext = mytext.replace('Z', 'W')
print mytext,

Example 3: replace characters in string python

>>> a = '&#'
>>> print a.replace('&', r'\&')
\&#
>>> print a.replace('#', r'\#')
&\#
>>>

Example 4: assigning a value to a character in string or text file in python

note:text can contain your text file that is already read or a string

text = 'hello'

vocab=sorted(set(text))
char_to_ind = {char:ind for ind,char in enumerate(vocab)}

Tags:

Java Example