Hướng dẫn dùng stringreplace python

❮ String Methods


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

ParameterDescriptionoldvalueRequired. The string to search fornewvalueRequired. The string to replace the old value withcountOptional. 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


Hàm replace() trong Python trả về một bản sao của chuỗi ban đầu sau khi đã thay thế các chuỗi con cũ bằng chuỗi con mới.


Cú pháp

Cú pháp của replace() trong Python:

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

Các tham số:

  • old: Đây là chuỗi con cũ để được thay thế.

  • new: Đây là chuỗi con mới để thay thế cho chuỗi con cũ.

  • max: Nếu tham số tùy ý max này được cung cấp, thì chỉ có các sự xuất hiện đầu tiên được thay thế.


Ví dụ sau minh họa cách sử dụng của hàm replace() trong Python.

str1 = "Vi du ham replace() Python"
print (str1.replace("Python", "Python tren VietTuts.Vn"))
print (str1.replace("ham", "phuong thuc", 1))

Chạy chương trình Python trên sẽ cho kết quả:

Vi du ham replace() Python tren VietTuts.Vn
Vi du phuong thuc replace() Python