Cara menggunakan STR.REPLACE pada Python

 			 		 		 		 		 	

Penggantian string seringkali penting. Jika Anda ingin mengganti string atau kata apa pun di program Anda, maka salah satu opsi adalah memeriksa seluruh program secara manual dan mengganti setiap string dengan string yang diinginkan. Python juga menyediakan fungsi replace() bawaan untuk penggantian string. Fungsi Python replace() tidak menggantikan string yang sebenarnya, tetapi membuat copyan string, dan menggantikan instance dari string yang ditentukan dengan string baru. Artikel ini menunjukkan cara menggunakan fungsi replace() dengan Python.

Sintaksis

Sintaks fungsi replace() adalah sebagai berikut:

 # replacing the "website" with "linuxhint"
print("replaced string is: ",str.replace("website","linuxhint"))

Keluaran

Output ditampilkan di konsol Python. Output ini menunjukkan bahwa istilah "situs web" telah diganti dengan istilah "linuxhint."

Cara menggunakan STR.REPLACE pada Python

Mari kita lihat contoh lain dari fungsi replace(). Di sini, kita akan mengganti istilah “anjing” dengan istilah “kucing”. Nilai hitungannya adalah 1, yang menunjukkan bahwa istilah "anjing" akan diganti dengan istilah "kucing" hanya sekali dalam string.

 # replacing the "Dog" with "Cat"
print(str.replace("Dog","Cat",1))

Keluaran

Output ditampilkan di konsol Python. Output ini menunjukkan bahwa istilah pertama "anjing" telah diganti dengan istilah "kucing" dalam string.

Cara menggunakan STR.REPLACE pada Python

Jika nilai hitungannya adalah 2, maka fungsi tersebut akan menggantikan dua kemunculan pertama dari istilah "anjing" dengan istilah "kucing" dalam string. Jika Anda tidak menggunakan nilai hitungan, maka fungsi replace() menggantikanall instance dari old_string yang ditentukan dengan new_string yang dipilih .

 # replacing the "Dog" with "Cat"
print(str.replace("Dog","Cat",2))

Keluaran

Output ditampilkan di konsol Python. Output ini menunjukkan bahwa dua kemunculan istilah "anjing" telah diganti dengan istilah "kucing" dalam string.

Cara menggunakan STR.REPLACE pada Python

Seperti yang dibahas sebelumnya, fungsi replace() hanya mengembalikan copyan string asli. Itu tidak mengubah string asli. Kami sekarang akan mencetak string asli setelah mengganti istilah "anjing" dengan istilah "kucing."

 # replacing the "Dog" with "Cat"
print("Replaced string: ",str.replace("Dog","Cat",2))
# printing the original string
print("Original String: ",str)

Keluaran

Output ditampilkan di konsol Python. Output ini menunjukkan bahwa string asli tetap sama. Fungsi replace() hanya mengembalikan copyan string asli setelah melakukan perubahan.

Cara menggunakan STR.REPLACE pada Python

Kesimpulan

Artikel ini menjelaskan penggantian string dengan Python menggunakan fungsi replace() dengan bantuan beberapa contoh sederhana. Artikel tersebut seharusnya membantu pemula untuk mempelajari lebih lanjut tentang melakukan penggantian string dengan Python menggunakan fungsi replace().

View Discussion

Table of Contents

  • Syntax of replace()
  • Replace All Instances of a Single Character using replace()
  • Replace All Instances of a String
  • Replace Only a Certain Number of Instances using replace()
  • Definition and Usage
  • Parameter Values
  • More Examples
  • Python String replace
  • Python String replace() example
  • Python string replace with count
  • String replace() example with user input
  • Want to learn more? Join the DigitalOcean Community!
  • Syntax of replace()
  • Replace All Instances of a Single Character using replace()
  • Replace All Instances of a String
  • Replace Only a Certain Number of Instances using replace()
  • How do I change the first 3 characters in Python?
  • How do I remove the first 3 characters of a string in Python?
  • How do you replace the first two characters of a string in Python?
  • How do you replace multiple characters in Python?

Table of Contents

  • Syntax of replace()
  • Replace All Instances of a Single Character using replace()
  • Replace All Instances of a String
  • Replace Only a Certain Number of Instances using replace()
  • Definition and Usage
  • Parameter Values
  • More Examples
  • Python String replace
  • Python String replace() example
  • Python string replace with count
  • String replace() example with user input
  • Want to learn more? Join the DigitalOcean Community!
  • Syntax of replace()
  • Replace All Instances of a Single Character using replace()
  • Replace All Instances of a String
  • Replace Only a Certain Number of Instances using replace()
  • How do I change the first 3 characters in Python?
  • How do I remove the first 3 characters of a string in Python?
  • How do you replace the first two characters of a string in Python?
  • How do you replace multiple characters in Python?

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The replace() in Python returns a copy of the string where all occurrences of a substring are replaced with another substring. 

    Syntax of replace()

    Syntax: string.replace(old, new, count)

    Parameters: 

    • old – old substring you want to replace.
    • new – new substring which would replace the old substring.
    • count – (Optional ) the number of times you want to replace the old substring with the new substring. 

    Return Value : It returns a copy of the string where all occurrences of a substring are replaced with another substring. 

    Replace All Instances of a Single Character using replace()

    In this example, we are only replacing a single character from a given string. The Python replace() method is case-sensitive, and therefore it performs a case-sensitive substring substitution, i.e. R in FOR is unchanged.

    Python3

    string = "grrks FOR grrks"

    new_string = string.replace("r", "e" )

    print(string)

    print(new_string)

    Output : 

    grrks FOR grrks
    geeks FOR geeks

    Replace All Instances of a String

    Here, we replaced all the geeks with GeeksforGeeks using replace() function.

    Python3

    string = "geeks for geeks \ngeeks for geeks"

    print(string)

    print(string.replace("geeks", "GeeksforGeeks"))

    Output : 

    geeks for geeks 
    geeks for geeks
    GeeksforGeeks for GeeksforGeeks 
    GeeksforGeeks for GeeksforGeeks

    Replace Only a Certain Number of Instances using replace()

    In this example, we are replacing certain numbers of words. i.e. “ek” with “a” with count=3.

    Python3

    string = "geeks for geeks geeks geeks geeks"

    print(string.replace("e", "a"))

    print(string.replace("ek", "a", 3))

    Output:  

    gaaks for gaaks gaaks gaaks gaaks
    geas for geas geas geeks geeks

    ❮ String Methods

    Table of Contents

    • Definition and Usage
    • Parameter Values
    • More Examples
    • Python String replace
    • Python String replace() example
    • Python string replace with count
    • String replace() example with user input
    • Want to learn more? Join the DigitalOcean Community!
    • Syntax of replace()
    • Replace All Instances of a Single Character using replace()
    • Replace All Instances of a String
    • Replace Only a Certain Number of Instances using replace()
    • How do I change the first 3 characters in Python?
    • How do I remove the first 3 characters of a string in Python?
    • How do you replace the first two characters of a string in Python?
    • How do you replace multiple characters in Python?

    Example

    Replace the word "bananas":

    txt = "I like bananas"

    x = txt.replace("bananas", "apples")

    print(x)

    Try it Yourself »


    Definition and Usage

    The replace() method replaces a specified phrase with another specified phrase.

    Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.


    Syntax

    string.replace(oldvalue, newvalue, count)

    Parameter Values

    ParameterDescription
    oldvalue Required. The string to search for
    newvalue Required. The string to replace the old value with
    count Optional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences

    More Examples

    Example

    Replace all occurrence of the word "one":

    txt = "one one was a race horse, two two was one too."

    x = txt.replace("one", "three")

    print(x)

    Try it Yourself »

    Example

    Replace the two first occurrence of the word "one":

    txt = "one one was a race horse, two two was one too."

    x = txt.replace("one", "three", 2)

    print(x)

    Try it Yourself »


    ❮ String Methods

    Python string replace() function is used to create a string by replacing some parts of another string.

    Python String replace

    Python String replace() function syntax is:

    str.replace(old, new[, count])
    

    The original string remains unmodified. The new string is a copy of the original string with all occurrences of substring old replaced by new. If optional argument count is provided, then only first count occurrences are replaced. We can use this function to replace characters in a string too.

    Python String replace() example

    Let’s look at some simple examples of using string replace() function.

    s = 'Java is Nice'
    
    # simple string replace example
    str_new = s.replace('Java', 'Python')
    print(str_new)
    
    # replace character in string
    s = 'dododo'
    str_new = s.replace('d', 'c')
    print(str_new)
    

    Output:

    Python is Nice
    cococo
    

    Python string replace with count

    s = 'dododo'
    str_new = s.replace('d', 'c', 2)
    print(str_new)
    

    Output: cocodo

    String replace() example with user input

    input_str = input('Please provide input data\n')
    delimiter = input('Please provide current delimiter\n')
    delimiter_new = input('Please provide new delimiter\n')
    output_str = input_str.replace(delimiter, delimiter_new)
    print('Updated Data =', output_str)
    

    Output:

    Please provide input data
    a,e,i,o,u
    Please provide current delimiter
    ,
    Please provide new delimiter
    :
    Updated Data = a:e:i:o:u
    
    We can also use str.replace() function as shown below.
    print(str.replace('abca', 'a', 'A'))
    

    Output: AbcA

    You can checkout complete script and more Python String examples from our GitHub Repository.

    Reference: API Doc

    Want to learn more? Join the DigitalOcean Community!

    Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

    Sign up

    View Discussion

    Improve Article

    Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The replace() in Python returns a copy of the string where all occurrences of a substring are replaced with another substring. 

    Syntax of replace()

    Syntax: string.replace(old, new, count)

    Parameters: 

    • old – old substring you want to replace.
    • new – new substring which would replace the old substring.
    • count – (Optional ) the number of times you want to replace the old substring with the new substring. 

    Return Value : It returns a copy of the string where all occurrences of a substring are replaced with another substring. 

    Replace All Instances of a Single Character using replace()

    In this example, we are only replacing a single character from a given string. The Python replace() method is case-sensitive, and therefore it performs a case-sensitive substring substitution, i.e. R in FOR is unchanged.

    Python3

    string = "grrks FOR grrks"

    new_string = string.replace("r", "e" )

    print(string)

    print(new_string)

    Output : 

    grrks FOR grrks
    geeks FOR geeks

    Replace All Instances of a String

    Here, we replaced all the geeks with GeeksforGeeks using replace() function.

    Python3

    string = "geeks for geeks \ngeeks for geeks"

    print(string)

    print(string.replace("geeks", "GeeksforGeeks"))

    Output : 

    geeks for geeks 
    geeks for geeks
    GeeksforGeeks for GeeksforGeeks 
    GeeksforGeeks for GeeksforGeeks

    Replace Only a Certain Number of Instances using replace()

    In this example, we are replacing certain numbers of words. i.e. “ek” with “a” with count=3.

    Python3

    string = "geeks for geeks geeks geeks geeks"

    print(string.replace("e", "a"))

    print(string.replace("ek", "a", 3))

    Output:  

    gaaks for gaaks gaaks gaaks gaaks
    geas for geas geas geeks geeks

    How do I change the first 3 characters in Python?

    Use Python built-in replace() function to replace the first character in the string. The str. replace takes 3 parameters old, new, and count (optional). Where count indicates the number of times you want to replace the old substring with the new substring.

    How do I remove the first 3 characters of a string in Python?

    Use Python to Remove the First N Characters from a String Using Regular Expressions. You can use Python's regular expressions to remove the first n characters from a string, using re's . sub() method. This is accomplished by passing in a wildcard character and limiting the substitution to a single substitution.

    How do you replace the first two characters of a string in Python?

    To replace the first N characters in a string using indexing, select all characters of string except the first n characters i.e. str[n:]. Then add these characters after the new replacement substring and assign it back to the original variable.

    How do you replace multiple characters in Python?

    A character in Python is also a string. So, we can use the replace() method to replace multiple characters in a string. It replaced all the occurrences of, Character 's' with 'X'.