Reference · Strings
replace
signature
replace(str, str, str) -> strWhat it does
The text with every occurrence of one piece replaced by another. The piece is plain text, not a pattern, and all of them are replaced, left to right, without overlapping; for a pattern use re.replace.
Examples
print(replace("a-b-c", "-", "+"))print(replace("hello world", "world", "there"))print(replace("a.b.c", ".", ""))output
a+b+chello thereabcEdge cases
- A piece that is not in the text leaves it unchanged; case matters.
- Matches do not overlap: in
"aaa","aa"is found once, and the result can be longer than the text, since each"a"can become"aa". - The empty piece matches between every character and at both ends, so
replace("hello", "", "-")is-h-e-l-l-o-, in the browser too. - Replacing the whole text with
""gives the empty string, and the empty text stays empty.
print(replace("hello", "x", "y"), replace("Hello", "h", "j"))print(replace("aaa", "aa", "b"), replace("aaa", "a", "aa"))print(replace("hello", "", "-"))print(replace("abc", "abc", ""), replace("", "a", "b"), replace("héllo", "é", "e"))output
hello Helloba aaaaaa-h-e-l-l-o- helloErrors
All three arguments are needed and must be strings; anything else is a runtime error,
not an error value. A number to put in is converted with str first.
this one fails
print(replace("abc", "a"))output
line 1: `replace` expects a str as argument 3, got nothingChaining
In a pipeline the text comes first, then the piece and its replacement:
print("hello world" | replace("world", "there") | upper)print(uuid() | replace("-", "") | len)print(["a_b", "c_d"] | map((s) => replace(s, "_", " ")))output
HELLO THERE32["a b", "c d"]See also
re.replace, split, join, trim, contains
Thread
Thread 0 posts
On replace(): questions, tips, corrections, and code that uses it.
No posts yet. The first one opens the thread.
Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo