Skip to main content
Log in

Mojo struct

StringLiteral

@register_passable(trivial) struct StringLiteral[value: string]

This type represents a string literal.

String literals are all null-terminated for compatibility with C APIs, but this is subject to change. String literals store their length as an integer, and this does not include the null terminator.

Parameters

  • value (string): The underlying string value.

Implemented traits

AnyType, Boolable, CollectionElement, CollectionElementNew, Copyable, ExplicitlyCopyable, FloatableRaising, IntableRaising, Movable, PathLike, PythonObjectible, Representable, Sized, Stringable, UnknownDestructibility, Writable, _CurlyEntryFormattable

Methods

__init__

__init__() -> Self

Constructor for any value.

__bool__

__bool__(self) -> Bool

Convert the string to a bool value.

Returns:

True if the string is not empty.

__getitem__

__getitem__[IndexerType: Index](self, idx: IndexerType) -> String

Gets the character at the specified position.

Parameters:

  • IndexerType (Index): The inferred type of an indexer argument.

Args:

  • idx (IndexerType): The index value.

Returns:

A new string containing the character at the specified position.

__lt__

__lt__(self, rhs: StringSlice[origin]) -> Bool

Compare this value to the RHS using lesser than (LT) comparison.

Args:

  • rhs (StringSlice[origin]): The other value to compare against.

Returns:

True if this is strictly less than the RHS and False otherwise.

__le__

__le__(self, rhs: StringSlice[origin]) -> Bool

Compare this value to the RHS using lesser than or equal to (LE) comparison.

Args:

  • rhs (StringSlice[origin]): The other value to compare against.

Returns:

True if this is less than or equal to the RHS and False otherwise.

__eq__

__eq__(self, rhs: StringSlice[origin]) -> Bool

Compare two string literals for equality.

Args:

  • rhs (StringSlice[origin]): The string to compare.

Returns:

True if they are equal.

__ne__

__ne__(self, rhs: StringSlice[origin]) -> Bool

Compare two string literals for inequality.

Args:

  • rhs (StringSlice[origin]): The string to compare.

Returns:

True if they are not equal.

__gt__

__gt__(self, rhs: StringSlice[origin]) -> Bool

Compare this value to the RHS using greater than (GT) comparison.

Args:

  • rhs (StringSlice[origin]): The other value to compare against.

Returns:

True if this is strictly greater than the RHS and False otherwise.

__ge__

__ge__(self, rhs: StringSlice[origin]) -> Bool

Compare this value to the RHS using greater than or equal to (GE) comparison.

Args:

  • rhs (StringSlice[origin]): The other value to compare against.

Returns:

True if this is greater than or equal to the RHS and False otherwise.

__add__

__add__(self, rhs: StringLiteral[value]) -> StringLiteral[#pop.string_concat<value, value>]

Concatenate two string literals.

Args:

  • rhs (StringLiteral[value]): The string to concat.

Returns:

The concatenated string.

__mul__

__mul__(self, n: Int) -> String

Concatenates the string n times.

Args:

  • n (Int): The number of times to concatenate the string.

Returns:

The string concatenated n times.

copy

copy(self) -> Self

Copy constructor.

Returns:

A copy of the value.

to_python_object

to_python_object(self) -> PythonObject

Convert this value to a PythonObject.

Returns:

A PythonObject representing the value.

__len__

__len__(self) -> Int

Get the string length.

Returns:

The length of this value.

__int__

__int__(self) -> Int

Parses the given string as a base-10 integer and returns that value. If the string cannot be parsed as an int, an error is raised.

Returns:

An integer value that represents the string, or otherwise raises.

__float__

__float__(self) -> SIMD[float64, 1]

Parses the string as a float point number and returns that value. If the string cannot be parsed as a float, an error is raised.

Returns:

A float value that represents the string, or otherwise raises.

__str__

__str__(self) -> String

Convert the string literal to a string.

Returns:

A new string.

__repr__

__repr__(self) -> String

Return a representation of this value.

You don't need to call this method directly, use repr("...") instead.

Returns:

A new representation of the string.

__fspath__

__fspath__(self) -> String

Return the file system path representation of the object.

Returns:

The file system path representation as a string.

__iter__

__iter__(self) -> CodepointSliceIter[StaticConstantOrigin]

Return an iterator over the string literal.

Returns:

An iterator over the string.

__reversed__

__reversed__(self) -> CodepointSliceIter[StaticConstantOrigin, False]

Iterate backwards over the string, returning immutable references.

Returns:

A reversed iterator over the string.

byte_length

byte_length(self) -> Int

Get the string length in bytes.

Notes: This does not include the trailing null terminator in the count.

Returns:

The length of this string in bytes.

unsafe_ptr

unsafe_ptr(self) -> UnsafePointer[SIMD[uint8, 1], mut=False, origin=StaticConstantOrigin]

Get raw pointer to the underlying data.

Returns:

The raw pointer to the data.

unsafe_cstr_ptr

unsafe_cstr_ptr(self) -> UnsafePointer[SIMD[int8, 1], mut=False, origin=StaticConstantOrigin]

Retrieves a C-string-compatible pointer to the underlying memory.

The returned pointer is guaranteed to be NUL terminated, and not null.

Returns:

The pointer to the underlying memory.

as_string_slice

as_string_slice(self) -> StringSlice[StaticConstantOrigin]

Returns a string slice of this static string literal.

Returns:

A string slice pointing to this static string literal.

as_bytes

as_bytes(self) -> Span[SIMD[uint8, 1], StaticConstantOrigin]

Returns a contiguous Span of the bytes owned by this string.

Returns:

A contiguous slice pointing to the bytes owned by this string.

write_to

write_to[W: Writer](self, mut writer: W)

Formats this string literal to the provided Writer.

Parameters:

  • W (Writer): A type conforming to the Writable trait.

Args:

  • writer (W): The object to write to.

find

find(self, substr: StringSlice[StaticConstantOrigin], start: Int = 0) -> Int

Finds the offset of the first occurrence of substr starting at start. If not found, returns -1.

Args:

  • substr (StringSlice[StaticConstantOrigin]): The substring to find.
  • start (Int): The offset from which to find.

Returns:

The offset of substr relative to the beginning of the string.

rfind

rfind(self, substr: StringSlice[StaticConstantOrigin], start: Int = 0) -> Int

Finds the offset of the last occurrence of substr starting at start. If not found, returns -1.

Args:

  • substr (StringSlice[StaticConstantOrigin]): The substring to find.
  • start (Int): The offset from which to find.

Returns:

The offset of substr relative to the beginning of the string.

count

count(self, substr: StringSlice[origin]) -> Int

Return the number of non-overlapping occurrences of substring substr in the string literal.

If sub is empty, returns the number of empty strings between characters which is the length of the string plus one.

Args:

  • substr (StringSlice[origin]): The substring to count.

Returns:

The number of occurrences of substr.

lower

lower(self) -> String

Returns a copy of the string literal with all cased characters converted to lowercase.

Returns:

A new string where cased letters have been converted to lowercase.

upper

upper(self) -> String

Returns a copy of the string literal with all cased characters converted to uppercase.

Returns:

A new string where cased letters have been converted to uppercase.

rjust

rjust(self, width: Int, fillchar: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string](" ")) -> String

Returns the string right justified in a string literal of specified width.

Args:

  • width (Int): The width of the field containing the string.
  • fillchar (StringSlice[StaticConstantOrigin]): Specifies the padding character.

Returns:

Returns right justified string, or self if width is not bigger than self length.

ljust

ljust(self, width: Int, fillchar: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string](" ")) -> String

Returns the string left justified in a string literal of specified width.

Args:

  • width (Int): The width of the field containing the string.
  • fillchar (StringSlice[StaticConstantOrigin]): Specifies the padding character.

Returns:

Returns left justified string, or self if width is not bigger than self length.

center

center(self, width: Int, fillchar: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string](" ")) -> String

Returns the string center justified in a string literal of specified width.

Args:

  • width (Int): The width of the field containing the string.
  • fillchar (StringSlice[StaticConstantOrigin]): Specifies the padding character.

Returns:

Returns center justified string, or self if width is not bigger than self length.

startswith

startswith(self, prefix: StringSlice[origin], start: Int = 0, end: Int = -1) -> Bool

Checks if the string literal starts with the specified prefix between start and end positions. Returns True if found and False otherwise.

Args:

  • prefix (StringSlice[origin]): The prefix to check.
  • start (Int): The start offset from which to check.
  • end (Int): The end offset from which to check.

Returns:

True if the self[start:end] is prefixed by the input prefix.

endswith

endswith(self, suffix: StringSlice[origin], start: Int = 0, end: Int = -1) -> Bool

Checks if the string literal end with the specified suffix between start and end positions. Returns True if found and False otherwise.

Args:

  • suffix (StringSlice[origin]): The suffix to check.
  • start (Int): The start offset from which to check.
  • end (Int): The end offset from which to check.

Returns:

True if the self[start:end] is suffixed by the input suffix.

isdigit

isdigit(self) -> Bool

Returns True if all characters in the string literal are digits.

Note that this currently only works with ASCII strings.

Returns:

True if all characters are digits else False.

isupper

isupper(self) -> Bool

Returns True if all cased characters in the string literal are uppercase and there is at least one cased character.

Note that this currently only works with ASCII strings.

Returns:

True if all cased characters in the string literal are uppercase and there is at least one cased character, False otherwise.

islower

islower(self) -> Bool

Returns True if all cased characters in the string literal are lowercase and there is at least one cased character.

Note that this currently only works with ASCII strings.

Returns:

True if all cased characters in the string literal are lowercase and there is at least one cased character, False otherwise.

strip

strip(self) -> String

Return a copy of the string literal with leading and trailing whitespaces removed. This only takes ASCII whitespace into account: " \t\n\v\f\r\x1c\x1d\x1e".

Returns:

A string with no leading or trailing whitespaces.

strip(self, chars: StringSlice[origin]) -> String

Return a copy of the string literal with leading and trailing characters removed.

Args:

  • chars (StringSlice[origin]): A set of characters to be removed. Defaults to whitespace.

Returns:

A string with no leading or trailing characters.

rstrip

rstrip(self, chars: StringSlice[origin]) -> String

Return a copy of the string literal with trailing characters removed.

Args:

  • chars (StringSlice[origin]): A set of characters to be removed. Defaults to whitespace.

Returns:

A string with no trailing characters.

rstrip(self) -> String

Return a copy of the string with trailing whitespaces removed. This only takes ASCII whitespace into account: " \t\n\v\f\r\x1c\x1d\x1e".

Returns:

A copy of the string with no trailing whitespaces.

lstrip

lstrip(self, chars: StringSlice[origin]) -> String

Return a copy of the string with leading characters removed.

Args:

  • chars (StringSlice[origin]): A set of characters to be removed. Defaults to whitespace.

Returns:

A copy of the string with no leading characters.

lstrip(self) -> String

Return a copy of the string with leading whitespaces removed. This only takes ASCII whitespace into account: " \t\n\v\f\r\x1c\x1d\x1e".

Returns:

A copy of the string with no leading whitespaces.