Hướng dẫn dùng stringreplace python
❮ String Methods ExampleReplace the word "bananas": txt = "I like bananas" x = txt.replace("bananas", "apples") print(x) Try it Yourself »Definition and UsageThe Note: All occurrences of the specified phrase will be replaced, if nothing else is specified. Syntaxstring.replace(oldvalue, newvalue, count) Parameter ValuesParameterDescriptionoldvalueRequired. 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 occurrencesMore ExamplesExampleReplace 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 »ExampleReplace 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ápCú pháp của replace() trong Python: str.replace(old, new[, max]) Các tham số:
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 |