This simple code that simply tries to replace semicolons (at i-specified postions) by colons does not work:
for i in range(0,len(line)):
if (line[i]==\"
Strings in python are immutable, so you cannot treat them as a list and assign to indices.
Use .replace() instead:
line = line.replace(';', ':')
If you need to replace only certain semicolons, you'll need to be more specific. You could use slicing to isolate the section of the string to replace in:
line = line[:10].replace(';', ':') + line[10:]
That'll replace all semi-colons in the first 10 characters of the string.
You cannot simply assign value to a character in the string. Use this method to replace value of a particular character:
name = "India"
result=name .replace("d",'*')
Output: In*ia
Also, if you want to replace say * for all the occurrences of the first character except the first character, eg. string = babble output = ba**le
Code:
name = "babble"
front= name [0:1]
fromSecondCharacter = name [1:]
back=fromSecondCharacter.replace(front,'*')
return front+back
To replace a character at a specific index, the function is as follows:
def replace_char(s , n , c):
n-=1
s = s[0:n] + s[n:n+1].replace(s[n] , c) + s[n+1:]
return s
where s is a string, n is index and c is a character.
If you are replacing by an index value specified in variable 'n', then try the below:
def missing_char(str, n):
str=str.replace(str[n],":")
return str
You can do this:
string = "this; is a; sample; ; python code;!;" #your desire string
result = ""
for i in range(len(string)):
s = string[i]
if (s == ";" and i in [4, 18, 20]): #insert your desire list
s = ":"
result = result + s
print(result)
If you want to replace a single semicolon:
for i in range(0,len(line)):
if (line[i]==";"):
line = line[:i] + ":" + line[i+1:]
Havent tested it though.