Skip to main content
Log in

Mojo struct

StringLiteral

@register_passable(trivial) struct StringLiteral

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.

Aliases

  • type = string:

Fields

  • value (string): The underlying storage for the string literal.

Implemented traits

AnyType, AsBytes, Boolable, BytesCollectionElement, CollectionElement, CollectionElementNew, Comparable, Copyable, EqualityComparable, EqualityComparableCollectionElement, ExplicitlyCopyable, FloatableRaising, Hashable, IntableRaising, KeyElement, Movable, Representable, Sized, Stringable, UnknownDestructibility, Writable, _CurlyEntryFormattable, _HashableWithHasher

Methods

__init__

@implicit __init__(out self, value: string)

Create a string literal from a builtin string type.

Args:

  • value (string): The string value.

__init__(out self, *, other: Self)

Copy constructor.

Args:

  • other (Self): The string literal to copy.

__bool__

__bool__(self) -> Bool

Convert the string to a bool value.

Returns:

True if the string is not empty.

__getitem__

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

Gets the character at the specified position.

Parameters:

  • IndexerType (Indexer): 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: Self) -> Bool

Compare this StringLiteral to the RHS using LT comparison.

Args:

  • rhs (Self): The other StringLiteral to compare against.

Returns:

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

__le__

__le__(self, rhs: Self) -> Bool

Compare this StringLiteral to the RHS using LE comparison.

Args:

  • rhs (Self): The other StringLiteral to compare against.

Returns:

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

__eq__

__eq__(self, rhs: Self) -> Bool

Compare two string literals for equality.

Args:

  • rhs (Self): The string to compare.

Returns:

True if they are equal.

__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: Self) -> Bool

Compare two string literals for inequality.

Args:

  • rhs (Self): The string to compare.

Returns:

True if they are not equal.

__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: Self) -> Bool

Compare this StringLiteral to the RHS using GT comparison.

Args:

  • rhs (Self): The other StringLiteral to compare against.

Returns:

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

__ge__

__ge__(self, rhs: Self) -> Bool

Compare this StringLiteral to the RHS using GE comparison.

Args:

  • rhs (Self): The other StringLiteral to compare against.

Returns:

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

__contains__

__contains__(self, substr: Self) -> Bool

Returns True if the substring is contained within the current string.

Args:

  • substr (Self): The substring to check.

Returns:

True if the string contains the substring.

__add__

__add__(self, rhs: Self) -> Self

Concatenate two string literals.

Args:

  • rhs (Self): The string to concat.

Returns:

The concatenated string.

__mul__

__mul__(self, n: IntLiteral) -> Self

Concatenates the string literal n times. Can only be evaluated at compile time using the alias keyword, which will write the result into The binary.

Examples:

alias concat = "mojo" * 3
print(concat) # mojomojomojo
alias concat = "mojo" * 3
print(concat) # mojomojomojo

.

Args:

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

Returns:

The string concatenated n times.

__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.

__iadd__

__iadd__(mut self, rhs: Self)

Concatenate a string literal to an existing one. Can only be evaluated at compile time using the alias keyword, which will write the result into the binary.

Example:

fn add_literal(
owned original: StringLiteral, add: StringLiteral, n: Int
) -> StringLiteral:
for _ in range(n):
original += add
return original


fn main():
alias original = "mojo"
alias concat = add_literal(original, "!", 4)
print(concat)
fn add_literal(
owned original: StringLiteral, add: StringLiteral, n: Int
) -> StringLiteral:
for _ in range(n):
original += add
return original


fn main():
alias original = "mojo"
alias concat = add_literal(original, "!", 4)
print(concat)

Result:

mojo!!!!
mojo!!!!

Args:

  • rhs (Self): The string to concat.

get

static get[value: String]() -> Self

Form a string literal from an arbitrary compile-time String value.

Parameters:

  • value (String): The value to convert to StringLiteral.

Returns:

The string value as a StringLiteral.

static get[type: Stringable, //, value: $0]() -> Self

Form a string literal from an arbitrary compile-time stringable value.

Parameters:

  • type (Stringable): The type of the value.
  • value ($0): The value to serialize.

Returns:

The string value as a StringLiteral.

__len__

__len__(self) -> Int

Get the string length.

Returns:

The length of this StringLiteral.

__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 the StringLiteral instance.

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

Returns:

A new representation of the string.

__hash__

__hash__(self) -> UInt

Hash the underlying buffer using builtin hash.

Returns:

A 64-bit hash value. This value is not suitable for cryptographic uses. Its intended usage is for data structures. See the hash builtin documentation for more details.

__hash__[H: _Hasher](self, mut hasher: H)

Updates hasher with the underlying bytes.

Parameters:

  • H (_Hasher): The hasher type.

Args:

  • hasher (H): The hasher instance.

__fspath__

__fspath__(self) -> String

Return the file system path representation of the object.

Returns:

The file system path representation as a string.

__iter__

__iter__(ref self) -> _StringSliceIter[StaticConstantOrigin]

Return an iterator over the string literal.

Returns:

An iterator over the string.

__reversed__

__reversed__(self) -> _StringSliceIter[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 StringLiteral 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.

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

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

Notes: This does not include the trailing null terminator.

Returns:

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

format

format[*Ts: _CurlyEntryFormattable](self, *args: *Ts) -> String

Format a template with *args.

Examples:

# Manual indexing:
print("{0} {1} {0}".format("Mojo", 1.125)) # Mojo 1.125 Mojo
# Automatic indexing:
print("{} {}".format(True, "hello world")) # True hello world
# Manual indexing:
print("{0} {1} {0}".format("Mojo", 1.125)) # Mojo 1.125 Mojo
# Automatic indexing:
print("{} {}".format(True, "hello world")) # True hello world

.

Parameters:

  • *Ts (_CurlyEntryFormattable): The types of substitution values that implement Representable and Stringable (to be changed and made more flexible).

Args:

  • *args (*Ts): The substitution values.

Returns:

The template with the given values substituted.

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: Self, start: Int = 0) -> Int

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

Args:

  • substr (Self): 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: Self, start: Int = 0) -> Int

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

Args:

  • substr (Self): The substring to find.
  • start (Int): The offset from which to find.

Returns:

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

replace

replace(self, old: Self, new: Self) -> Self

Return a copy of the string with all occurrences of substring old if replaced by new. This operation only works in the param domain.

Args:

  • old (Self): The substring to replace.
  • new (Self): The substring to replace with.

Returns:

The string where all occurrences of old are replaced with new.

join

join[T: StringableCollectionElement](self, elems: List[T, hint_trivial_type]) -> String

Joins string elements using the current string as a delimiter.

Parameters:

  • T (StringableCollectionElement): The types of the elements.

Args:

  • elems (List[T, hint_trivial_type]): The input values.

Returns:

The joined string.

join(self, *elems: Int) -> String

Joins the elements from the tuple using the current string literal as a delimiter.

Args:

  • *elems (Int): The input tuple.

Returns:

The joined string.

join[*Types: Stringable](self, *elems: *Types) -> String

Joins string elements using the current string as a delimiter.

Parameters:

  • *Types (Stringable): The types of the elements.

Args:

  • *elems (*Types): The input values.

Returns:

The joined string.

split

split(self, sep: String, maxsplit: Int = -1) -> List[String]

Split the string literal by a separator.

Examples:

# Splitting a space
_ = "hello world".split(" ") # ["hello", "world"]
# Splitting adjacent separators
_ = "hello,,world".split(",") # ["hello", "", "world"]
# Splitting with maxsplit
_ = "1,2,3".split(",", 1) # ['1', '2,3']
# Splitting a space
_ = "hello world".split(" ") # ["hello", "world"]
# Splitting adjacent separators
_ = "hello,,world".split(",") # ["hello", "", "world"]
# Splitting with maxsplit
_ = "1,2,3".split(",", 1) # ['1', '2,3']

.

Args:

  • sep (String): The string to split on.
  • maxsplit (Int): The maximum amount of items to split from String. Defaults to unlimited.

Returns:

A List of Strings containing the input split by the separator.

split(self, sep: NoneType = None, maxsplit: Int = -1) -> List[String]

Split the string literal by every whitespace separator.

Examples:

# Splitting an empty string or filled with whitespaces
_ = " ".split() # []
_ = "".split() # []

# Splitting a string with leading, trailing, and middle whitespaces
_ = " hello world ".split() # ["hello", "world"]
# Splitting adjacent universal newlines:
_ = "hello \t\n\v\f\r\x1c\x1d\x1e\x85\u2028\u2029world".split()
# ["hello", "world"]
# Splitting an empty string or filled with whitespaces
_ = " ".split() # []
_ = "".split() # []

# Splitting a string with leading, trailing, and middle whitespaces
_ = " hello world ".split() # ["hello", "world"]
# Splitting adjacent universal newlines:
_ = "hello \t\n\v\f\r\x1c\x1d\x1e\x85\u2028\u2029world".split()
# ["hello", "world"]

.

Args:

  • sep (NoneType): None.
  • maxsplit (Int): The maximum amount of items to split from string. Defaults to unlimited.

Returns:

A List of Strings containing the input split by the separator.

splitlines

splitlines(self, keepends: Bool = False) -> List[String]

Split the string literal at line boundaries. This corresponds to Python's universal newlines: "\r\n" and "\t\n\v\f\r\x1c\x1d\x1e\x85\u2028\u2029".

Args:

  • keepends (Bool): If True, line breaks are kept in the resulting strings.

Returns:

A List of Strings containing the input split by line boundaries.

count

count(self, substr: String) -> 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 (String): 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: Self = " ") -> 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 (Self): 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: Self = " ") -> 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 (Self): 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: Self = " ") -> 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 (Self): Specifies the padding character.

Returns:

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

startswith

startswith(self, prefix: String, 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 (String): 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: String, 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 (String): 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: String) -> String

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

Args:

  • chars (String): A set of characters to be removed. Defaults to whitespace.

Returns:

A string with no leading or trailing characters.

rstrip

rstrip(self, chars: String) -> String

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

Args:

  • chars (String): 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: String) -> String

Return a copy of the string with leading characters removed.

Args:

  • chars (String): 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.