replace()#
relationalai.std.strings
#replace(string: str|Producer, old: str|Producer, new: str|Producer) -> Expression
Replaces all occurrences of a substring in a string.
If any of the arguments are Producer
objects, replace()
acts as a filter and removes non-string values from the producer.
Must be called in a rule or query context.
Parameters#
Name | Type | Description |
---|---|---|
string | str or Producer | A string or a producer that produces string values. |
old | str or Producer | The substring to replace. |
new | str or Producer | The substring to replace old with. |
Returns#
An Expression
object.
Example#
#import relationalai as rai
from relationalai.std import strings
# =====
# SETUP
# =====
model = rai.Model("MyModel")
Person = model.Type("Person")
with model.rule():
Person.add(id=1).set(name="Alice")
Person.add(id=2).set(name="Bob")
Person.add(id=3).set(name=-1) # Non-string name
# =======
# EXAMPLE
# =======
# Set a new_name property equal to the name property with all occurrences of
# "ice" replaced with "icia".
with model.rule():
person = Person()
person.set(new_name=strings.replace(person.name, "ice", "icia"))
# Since replace() filters out non-string values, the new_name property is not
# set for the person with id=3.
with model.query() as select:
person = Person()
response = select(person.id, person.name, person.new_name)
print(response.results)
# id name new_name
# 0 1 Alice Alicia
# 1 2 Bob Bob
# 2 3 -1 NaN