-1

I am Trying to replace a substring in a sentence. Example: Name Id = Name_ID
Date of Birth = Date_of_Birth
Admission Type = Admission_Type
I have tried the below code
But it does not seem to work.

line = "Name Name Id Username Date of Birth Admission Type"
line.replace("Name Id","Name_ID",1)
line.replace("Date of Birth","Date_of_Birth")
line.replace("Admission Type","Admission_Type"



Expected Output:
line = "Name Name_Id Username Date_of_Birth Admission_Type"

My code Output:
line = "Name Name Id Username Date of Birth Admission Type"

1 Answers1

0

replace() does not mutate the string you provide to it. You need to reassign line to the string that is returned by replace():

line = "Name Name Id Username Date of Birth Admission Type"
line = line.replace("Name Id","Name_ID",1)
line = line.replace("Date of Birth","Date_of_Birth")
line = line.replace("Admission Type","Admission_Type"

Documentation

string.replace(s, old, new[, maxreplace]) Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced

Num Lock
  • 742
  • 1
  • 6
  • 32