substring()#

relationalai.std.strings
#substring(string: str|Producer, start: int|Producer, end: int|Producer) -> Expression

Extracts a substring from a string between the specified zero-based start and end indices, inclusive. If start is negative, the substring starts from the first character, and if end is greater than the largest index, the substring ends at the last character. Returns the empty string if start > end or end < start. If any of the arguments are Producer objects, substring() acts as a filter and removes invalid values from the producer. Must be called in a rule or query context.

Parameters#

NameTypeDescription
stringProducer or Python str objectThe string to extract a substring from.
startProducer or Python int objectThe zero-based starting index of the substring.
endProducer or Python int objectThe zero-based ending index of the substring.

Returns#

An Expression object.

Example#

Use substring() to extract a substring from a string:

#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 short_name property equal to the first three characters of the name property.
with model.rule():
    person = Person()
    person.set(short_name=strings.substring(person.name, 0, 2))

# substring() filters out non-string values, so the short_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.short_name)

print(response.results)
#    id   name short_name
# 0   1  Alice        Ali
# 1   2    Bob        Bob
# 2   3     -1        NaN

# If the start index is negative, the substring starts from the first character,
# and if the end index is greater than the largest index, the substring ends at
# the last character.
with model.query() as select:
    person = Person()
    response = select(person.name, substring(person.name, -3, 100))

print(response.results)
#     name      v
# 0  Alice  Alice
# 1    Bob    Bob

# If `start > end` or `end < start`, the empty string is returned.
with model.query() as select:
    person = Person()
    response = select(person.name, substring(person.name, 2, 1))

print(response.results)
#     name v
# 0  Alice
# 1    Bob

See Also#