substring()#

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

Extracts a substring from a string between the specified start and end indices, inclusive. Must be called in a rule or query context.

Parameters#

NameTypeDescription
stringstr or ProducerThe string to extract a substring from.
startint or ProducerThe zero-based starting index of the substring.
endint or ProducerThe zero-based ending index of the substring.

Returns#

An Expression object.

Example#

#import relationalai as rai
from relationalai.std.strings import substring

# =====
# SETUP
# =====

# Create a model named "people" with a Person type.
model = rai.Model("people")
Person = model.Type("Person")

# Add some people to the model.
with model.rule():
    Person.add(id=1).set(name="Alice")
    Person.add(id=2).set(name="Bob")

# =======
# EXAMPLE
# =======

# Get the first three characters of each person's name.
with model.query() as select:
    person = Person()
    first_three = substring(person.name, 0, 2)
    response = select(person.name, first_three)

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

If start is negative, the substring starts from the first character. If end 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#