![]() ![]() Suppose let us consider if we want to c: \home as a replacement string, then we specify the expression in the sub() method as r”c:\\home”. Hence it would help if you used raw string for replacing the string. The sub() function uses backslash, which has the same concept as in the regular expression for replacement of the text. Hence again, we use the sub () method, which replaces the entire string to be only digits by using a regular expression as “\D” is replaced by nothing, but it should contain only digits. So we have first obtained a phone number where we have specified a sub() method where we are replacing the string starting from “#” and everything till the end so we obtain the phone number as “2004-959-559”, but as we know, there should not be any special characters in a phone number as it is a numerical value. Print("Now we have replaced all the spaces and have only digits in the given string is as follows:")Įxplanation: In the above program, we can see that we have a string with a variable name “phonenum”, which we have a string with phone number also, but we need only digits for obtaining proper phone number. Print("The correct phone number by removing special characters in the given string which means replacing them by space is as follows:")Ĭorrect_num2 = re.sub(r'\D', "", phonenum) ![]() Print("The below program is used to demonstrate sub() method:") Now let us see an example below that uses this sub() method: This method returns the modified string after the replacement of the string is done. This sub() method is used to replace all the given “re” pattern in the string, which is in the replc parameter and substituting all occurrences unless the max value is specified.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |