C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python String replace() MethodReturn a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. Signaturereplace(old, new[, count]) Parametersold : An old string which will be replaced. new : New string which will replace the old string. count : The number of times to process the replace. ReturnIt returns string Let's see some examples of replace() method to understand it's functionality. Python String replace() Method Example 1# Python replace() method example # Variable declaration str = "Java is a programming language" # Calling function str2 = str.replace("Java","C") # Displaying result print("Old String: \n",str) print("New String: \n",str2) Output: Old String: Java is a programming language New String: C is a programming language Python String replace() Method Example 2# Python replace() method example # Variable declaration str = "Java C C# Java Php Python Java" # Calling function str2 = str.replace("Java","C#") # replaces all the occurences # Displaying result print("Old String: \n",str) print("New String: \n",str2) # Calling function str2 = str.replace("Java","C#",1) # replaces first occurance only # Displaying result print("\n Old String: \n",str) print("New String: \n",str2) Output: Old String: Java C C# Java Php Python Java New String: C# C C# C# Php Python C# Old String: Java C C# Java Php Python Java New String: C# C C# Java Php Python Java Python String replace() Method Example 3# Python replace() method example # Variable declaration str = "Apple is a fruit" # calling function str2 = str.replace(str,"Tomato is also a fruit") # displaying result print(str2) Output: Tomato is also a fruit
Next TopicPython Strings
|